这是我第一次在这里发帖提问。我是java的新手,目前正在上一门课程。这是作业:“修改你的按钮GUI程序,这样按钮每隔一秒就会改变颜色,除非它们被按下。” ......这就是我给出的所有指示。哈哈,它什么都没有!
所以我现在知道,当点击按钮时,它变成白色并停止变化。从技术上讲,满足给出的指示,对吧?我不认为这是他们想要的东西......而且我只是改变了不透明度,所以它仍在改变颜色,你只是看不到它,对吧?所以我想知道的是,是否有办法可以阻止按钮改变颜色,但保持它已经有的颜色,如冻结,而不是将其变成白色?我有一个静态JFrame jf,在main外面按下静态Boolean和所有正确的导入。我的getColor()函数只返回一个随机颜色。感谢您的帮助/建议!!
public static void main(String[] args) {
jf = new JFrame("Homework 2");//constructed
jf.setSize(400,400);//sets window size
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//closes program
jf.setLayout(new GridLayout(2,4));
ArrayList<JButton> buttons = new ArrayList<JButton>();//array of button
pressed = true;
for(int i=1; i <= 8; i++) { //creates 8 buttons
JButton jb = new JButton();
jb.setText("Button " + i);
jb.setOpaque(pressed);
jb.setBorderPainted(false);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton theButton = (JButton)e.getSource();
theButton.setOpaque(!pressed);//makes it white if it has been clicked
}
});
buttons.add(jb);//add the button to the array
jf.add(jb);//adding to frame
}
jf.setVisible(true);//makes the window appear
while(true) {
for (JButton button : buttons){
button.setBackground(getColor());//change colors
}
try {
Thread.sleep(1000);//unless
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
要从进一步的颜色更改中删除(停止)按钮,请在执行操作时将其从buttons
数组列表中删除。
我会创建一个8个布尔数组来跟踪按钮。并在此处检查按钮是否应更改其颜色:
for (int i = 0; i < 8; ++i){
if(!pressedArr[i]){
button.setBackground(getColor());//change colors
}
}
此外,您需要跟踪所有八个值,当所有这些值都是true
时,只需突破while
循环