题目: 编写一个窗体应用,点击按钮让按钮的背景颜色随机变化。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class gui extends JFrame{
public void aa(String title) {
JFrame a = new JFrame(title);
a.setSize(400,300);
a.setVisible(true);
a.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container bb = a.getContentPane();
bb.setBackground(Color.yellow);
JButton button = new JButton("按钮");
bb.add(button);
button.setBounds(100, 100, 100, 80);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random rd=new Random();
int r=rd.nextInt(255);
int g=rd.nextInt(255);
int b=rd.nextInt(255);
Color color=new Color(r,g,b);
button.setBackground(color);
}
});
}
public static void main(String arge[]) {
new gui().aa("按钮");
}
}
运行截图如下: