我正在尝试用 Java 制作一个游戏,如果你点击一个按钮,一旦它变成红色,如果你点击它两次,它就会变成蓝色,但是我遇到了一个问题,当我点击一个方 block 一次它变成红色,如果我点击另一个一旦它变成蓝色,当我想要一次将效果隔离到每个方 block 时(例如,如果我点击一个方 block 一次它是红色,点击另一个方 block 两次它的蓝色,另一个方 block 一次它的红色) .我还希望它在点击 3 次后重置。
到目前为止,这是我的 Action 监听器
JFrame frame = new JFrame(); //creates frame
JButton[][] grid; //names the grid of buttons
int clicked = 0;
public ButtonGrid(int width, int length) { //constructor
frame.setLayout(new GridLayout(width, length)); //set layout
grid = new JButton[width][length]; //allocate the size of grid
for(int y = 0; y < length; y++) {
for(int x = 0; x < width; x++) {
grid[x][y] = new JButton(); //creates a button
grid[x][y].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(clicked == 0) {
((JButton)e.getSource()).setBackground(Color.red);
clicked++;
} else if(clicked == 1) {
((JButton)e.getSource()).setBackground(Color.blue);
clicked++;
}
}
});
frame.add(grid[x][y]); //adds new button to grid
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
// ...
}
最佳答案
在您当前的实现中,clicked
是父类的一个实例字段,您的所有按钮/ActionListener
都在使用它。
相反,您需要隔离该属性,以便它可以更好地与单个按钮相关联。
现在,您可以创建一个自定义类,该类扩展
自 JButton
,但恕我直言,这有点笨拙并且将您锁定在一个用例中。就个人而言,我希望实现 ActionListener
的具体实现以提供这种副作用。
例如……
public class CounterActionListener implements ActionListener {
private int counter;
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton button = (JButton)source;
clicked++;
if(clicked == 0) {
button.setBackground(Color.red);
} else if(clicked == 1){
button.setBackground(Color.blue);
}
}
}
}
然后在您的代码中,您只需将监听器应用于按钮,例如...
grid[x][y] = new JButton(new CounterActionListener());
您还可以通过使用“委托(delegate)”来实现这一点,它实际上根据点击次数执行了所需的操作,这可以保存在模型中,但这超出了问题的范围;)
关于java - 如何使按钮在不同的点击量上发生变化java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50091814/