import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class JFrameTest extends JFrame implements ActionListener {
static int i = 0;
Random r = new Random();
JButton[] jb = new JButton[5];
public static void main(String[] args) {
new JFrameTest();
}
public JFrameTest() {
for (int i = 0; i < jb.length; i++) {
jb[i] = new JButton("颜色" + i + "号");
}
this.add(jb[0], BorderLayout.EAST);
this.add(jb[1], BorderLayout.SOUTH);
this.add(jb[2], BorderLayout.WEST);
this.add(jb[3], BorderLayout.NORTH);
this.add(jb[4], BorderLayout.CENTER);
// 注册监听
jb[0].addActionListener(this);
jb[0].setActionCommand("jb[0]");
jb[1].addActionListener(this);
jb[1].setActionCommand("jb[1]");
jb[2].addActionListener(this);
jb[2].setActionCommand("jb[2]");
jb[3].addActionListener(this);
jb[3].setActionCommand("jb[3]");
this.setTitle("颜色案例");
this.setSize(600, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
System.out.println("********" + (i++));
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("jb[0]")) {
jb[4].setBackground(new Color(r.nextInt(256), r.nextInt(256), r
.nextInt(256), r.nextInt(256)));
} else if (e.getActionCommand().equals("jb[1]")) {
jb[4].setBackground(new Color(r.nextInt(256), r.nextInt(256), r
.nextInt(256), r.nextInt(256)));
} else if (e.getActionCommand().equals("jb[2]")) {
jb[4].setBackground(new Color(r.nextInt(256), r.nextInt(256), r
.nextInt(256), r.nextInt(256)));
} else if (e.getActionCommand().equals("jb[3]")) {
jb[4].setBackground(new Color(r.nextInt(256), r.nextInt(256), r
.nextInt(256), r.nextInt(256)));
} else {
System.out.println("啥都不做");
}
this.repaint();
}
}