题目:编写一个程序,实现一个图形用户界面。在该界面上有一个静态文本框,里面有一段文字。另外还有两个单选按钮,用于设置文字的颜色:蓝色或红色。当用户选定某个颜色后,文本框中文字的颜色随机发生了变化。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MouseEventDemo extends JPanel implements ActionListener{
JLabel label;
public static void main(String[] args){
MouseEventDemo demo = new MouseEventDemo();
demo.go();
}
public void go(){
JFrame f = new JFrame("图形用户界面");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton button1 = new JButton("红色");
JButton button2 = new JButton("蓝色");
label = new JLabel("信息科学与技术学院");
f.getContentPane().add(label);
f.getContentPane().add(button1);
f.getContentPane().add(button2);
f.setSize(500,100);
f.setVisible(true);
button1.addActionListener(this);
button2.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if("红色".equals(str)) {
label.setForeground(Color.RED);
}else {
label.setForeground(Color.BLUE);
}
}
}
运行效果: