九宫格色板,为按钮加载监听器

/*
  1. 使用网格布局将容器分红3*3大小相同的网格
  2. 9个按钮添加事件
  3. 9个按钮放在9个格子里   */
 
 

package priv.xiaomin.colorpane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;java

 
 


public class ColorPane extends JFrame implements ActionListener {
private GridLayout gridLayout;
private Container container;
private JButton buttons[];
boolean flag[]={true,true,true,true,true,true,true,true,true};
public ColorPane() {
super("ColorPane");
gridLayout=new GridLayout(3, 3);
container=getContentPane();
container.setLayout(gridLayout);
buttons=new JButton[9];
buttons[0]=new JButton("blue");
buttons[1]=new JButton("cyan");
buttons[2]=new JButton("green");
buttons[3]=new JButton("magenta");
buttons[4]=new JButton("orange");
buttons[5]=new JButton("pink");
buttons[6]=new JButton("red");
buttons[7]=new JButton("white");
buttons[8]=new JButton("yellow");
for(int i=0;i<9;i++){
buttons[i].addActionListener(this);
container.add(buttons[i]);
}
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
ColorPane colorPane=new ColorPane();
colorPane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);布局

 
 

}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==buttons[0]){
if(flag[0] == true){
buttons[0].setBackground(Color.blue);
}
else {
buttons[0].setBackground(null);
}
flag[0] = !flag[0];
}
else if(e.getSource()==buttons[1]){
if(flag[1] == true){
buttons[1].setBackground(Color.cyan);
}
else {
buttons[1].setBackground(null);
}
flag[1] = !flag[1];
}
else if(e.getSource()==buttons[2]){
if(flag[2] == true){
buttons[2].setBackground(Color.green);
}
else {
buttons[2].setBackground(null);
}
flag[2] = !flag[2];
}
else if(e.getSource()==buttons[3]){
if(flag[3] == true)
buttons[3].setBackground(Color.magenta);
else {
buttons[3].setBackground(null);
}
flag[3] = !flag[3];
}
else if(e.getSource()==buttons[4]){
if(flag[4] == true)
buttons[4].setBackground(Color.orange);
else {
buttons[4].setBackground(null);
}
flag[4] = !flag[4];
}
else if(e.getSource()==buttons[5]){
if(flag[5] == true)
buttons[5].setBackground(Color.pink);
else {
buttons[5].setBackground(null);
}
flag[5] = !flag[5];
}
else if (e.getSource()==buttons[6]) {
if(flag[6] == true)
buttons[6].setBackground(Color.red);
else {
buttons[6].setBackground(null);
}
flag[6] = !flag[6];
}
else if(e.getSource()==buttons[7]){
if(flag[7] == true)
buttons[7].setBackground(Color.white);
else {
buttons[7].setBackground(null);
}
flag[7] = !flag[7];
}
else if(e.getSource()==buttons[8]){
if(flag[8] == true)
buttons[8].setBackground(Color.yellow);
else {
buttons[8].setBackground(null);
}
flag[8] = !flag[8];
}
}
}this

 

/*须要注意的一个问题是第一次点击某一块色板时,色斑变色,第二次点击色板时,要变回原色*/spa