我创建了一个 JButton 数组,在创建时为它们分配了随机颜色,而不是手动创建每个按钮并为它们分配随机颜色。我现在正处于我想随机更改单击的任何按钮的颜色的地步。我想以与迄今为止创建和添加按钮相同的方式进行操作(通过使用循环)。
尽管按照我认为可行的方式进行操作失败了。我被给了"local variable is accessed from within inner class; needs to be declared final"
。我是,如果我使用 final 它不能改变,现在我很茫然。
有可能的解决方法吗?
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.EventHandler;
import java.lang.String;
import java.util.Random;
public class TEST
{
/**
* @param args the command line arguments
*/
public static Random rand = new Random();
public static int oh;
public void btnPress(ActionEvent e, JButton[] jButts, float r, float g, float b) {
for (int y = 0; y < jButts.length; y++) {
if (e.getSource() == jButts[y]) {
jButts[y].setBackground(Color.getHSBColor(r, g, b));
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Suhp, Brah?");
frame.setLayout(new BorderLayout());
frame.setVisible(true);
frame.setBackground(Color.magenta);
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(4, 4));
String[] numbs = {"0", "1", "2", "3", "4", "5", "6", "7"};
final JButton[] jButts = new JButton[numbs.length];//0-7
for (int i = 0; i < 8; i++) {
jButts[i] = new JButton(numbs[i].toString());
//String leString = rand.nextInt(255).toString;
jButts[i].setBackground(Color.getHSBColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
}
for (int x = 0; x < 8; x++) {
frame.add(jButts[x]);
}
//ActionListener
for (int i =0; i < 8; i++) {
jButts[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
i++;
jButts[i].setBackground(Color.getHSBColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
}
});
}
}
}