【发布时间】:2019-09-02 16:03:39
【问题描述】:
我正在创建一个由 4 x 2 按钮组成的网格,我希望它们不断改变颜色。一旦我按下按钮,它就会停止改变颜色。如果我按下一个按钮并让其他按钮连续改变颜色,我很难弄清楚如何让那个按钮停止改变颜色。如果我按下另一个按钮,该按钮也会停止改变颜色。
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();
}
}
}
【问题讨论】:
-
如果在 main 方法中保留一个布尔数组
hasBeenPressed[buttonNumber],并且在嵌套循环 (j) 内部,有一个 if 语句检查值并只让按钮更新它,该怎么办?如果布尔数组中的对应值为真,则颜色?
标签: java web-development-server