编写程序,如下所示。要求每单击一次按钮,窗口的背景颜色就随机改变一次。(颜色通过Color类自定义颜色值随机产生)
仅供学习
package day01;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Text5 {
public static class cannian extends JFrame {
JPanel ac;
JButton a;
public cannian() {
super("调色板");
ac=new JPanel();
a = new JButton("颜色变变变");
ac.add(a);
ButtonListener b1 = new ButtonListener();
a.addActionListener(b1);
this.setSize(300, 200);
this.setLocation(100, 100);
this.add(ac);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//创建扩展ActionListener的监听类
public class ButtonListener implements ActionListener {
//重写ActionListener接口中的事件处理方法actionPerformed()
public void actionPerformed(ActionEvent e) {
Object source =e.getSource();
if(source==a){
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);
ac.setBackground(color);
}
}
}
public static void main(String[] args) {
cannian abc=new cannian();
abc.setVisible(true);
}
}
}