[英]While buttons are changing color every second, how do I make the button I press stop while the other buttons continue switching colors?
I am creating a grid of 4 by 2 buttons and I want them to continuously change color. 我正在创建一个4乘2按钮的网格,我希望它们能够不断改变颜色。 A button will stop changing colors once I press it. 按下按钮后,按钮将停止更改颜色。 I have having trouble figuring how to make that one button stop changing colors if I press on it and have other buttons to continuously change color. 如果按下它并让其他按钮连续改变颜色,我无法确定如何使一个按钮停止改变颜色。 If I press another button, that button stops changing color as well. 如果我按下另一个按钮,该按钮也会停止改变颜色。
public class Hw1 extends JPanel {
static JFrame jf;
static JPanel jp;
static JButton jb;
public static void main(String[] args) {
jf = new JFrame("Hello World!");
int xAxis = 500;
int yAxis = 300;
jf.setSize(xAxis, yAxis);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp = new JPanel();
int num = 8;
JButton[] buttonList = new JButton[num];
int count = 0;
// creates buttons and initially assigns random color
for(int i = 0; i < 2 ; i++){
for(int j = 0; j < 4; j++){
jb = new JButton("press me!");
jb.setBounds(i * (xAxis/2), j * (yAxis/4), xAxis/2, yAxis/4);
jb.setVisible(true);
jb.setOpaque(true);
int primeR = (int)(Math.random() * 255+ 0);
int primeG = (int)(Math.random() * 255 + 0);
int primeB = (int)(Math.random() * 255 + 0);
Color random = new Color(primeR, primeG, primeB);
jb.setBackground(random);
// adds action listener to each button aka checks if button is pressed
jb.addActionListener(new ActionListener(){
// action if button is pressed
//if pressed change stop changing colors
public void actionPerformed(ActionEvent ae) {
JButton theButton = (JButton)ae.getSource();
theButton.setBackground(random);
}
});
buttonList[count] = jb;
count++;
jp.add(jb);
}
}
jf.add(jp);
jf.setVisible(true);
for (int k = 0; k < buttonList.length; k++) {
new Thread(){
public void run(){
while(true){
try {
sleep(1000);
}
catch (InterruptedException ex) {
}
for (int i = 0; i < buttonList.length; i++) {
int primeR = (int)(Math.random() * 255);
int primeG = (int)(Math.random() * 255);
int primeB = (int)(Math.random() * 255);
Color random = new Color(primeR, primeG, primeB);
buttonList[i].setBackground(random);
}
}
}
}.start();
}
}
} }
you need to keep state of button. 你需要保持按钮状态。 If you have grid of 4 button, make an array of it's state buttonState = new Boolean[2][2]
如果您有4个按钮的网格,请创建一个状态的数组buttonState = new Boolean[2][2]
when button on position x,y is pressed, set value of [x][y] to true. 按下位置x,y上的按钮时,将[x] [y]的值设置为true。 check buttonState
before changing color of button. 在更改按钮颜色之前检查buttonState
。
OR 要么
Overwrite JButton and add bolean field pressed
to it, and set it to true in onClick
, and based on that value change or not change color 覆盖JButton并添加pressed
bolean字段,并在onClick
中将其设置为true,并根据该值更改或不更改颜色
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.