改变Jbuttons数组的颜色

时间:2016-03-14 03:58:39

标签: java user-interface jbutton

我有一个5x5的Jbutton布局,我每次点击一个按钮都试图改变Jbutton的颜色。

我想要做的是每次点击Jbutton时它会改变颜色并从这个数组中选择一种颜色。 这就是我用随机颜色初始化按钮的方法。

Color[] colors = new Color[4];

//Initialize the values of the array
colors[0] = Color.red;
colors[1] = Color.blue;
colors[2] = Color.yellow;
colors[3] = Color.green;


for(int row=0; row<5; row++) {
    for (int col=0; col<5; col++) {
        buttons[row][col] = new JButton(buttonLabels[row*5+col]);
        buttons[row][col].setLocation(10+col*55, 10+row*55);
        buttons[row][col].setSize(50,50);
        buttons[row][col].addActionListener(this);

        buttons[row][col].setBackground(colors[new Random().nextInt(4)]);

        add(buttons[row][col]);
    }
}    

这是我的actionPerfomred方法。当我点击一个按钮时,这会给我一个错误而且什么都不做。

public void actionPerformed(ActionEvent e) {
JButton selectedBtn = (JButton) e.getSource();

for (int row = 0; row < buttons.length; row++) {
  for (int col = 0; col < buttons[row].length; col++) {
    if(index < (colors.length - 1))
    {
        index++;
    }
    else
    {
        index = 0;
    }
    buttons[row][col].setBackground(colors[index]);
  }
 }
}

对此有何帮助?

0 个答案:

没有答案