【发布时间】:2019-04-11 16:43:24
【问题描述】:
这是我第一次在这里发布问题。我是 java 新手,目前正在学习它的课程。这是任务:“修改你的按钮 GUI 程序,使按钮大约每秒钟改变一次颜色,除非它们被按下。” ...这就是我得到的所有指示。哈哈,什么都没有!
所以我现在知道,当单击按钮时,它会变成白色并停止变化。从技术上讲,这满足了给出的说明,对吧?我不认为那是他们想要的……而且我只是在改变不透明度,所以它仍然在改变颜色,你只是看不到它,对吧?所以我想知道是否有一种方法可以阻止按钮改变颜色但保持它已经拥有的颜色就像冻结它,而不是把它变成白色?我有一个静态 JFrame jf,在 main 和所有正确的导入之外按下静态布尔值。我的 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();
}
}
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2)不要阻塞EDT(事件调度线程)。发生这种情况时,GUI 将“冻结”。有关详细信息和修复,请参阅Concurrency in Swing。 3) 若要从进一步的颜色变化中移除(停止)按钮,请在执行操作时将其从
buttons数组列表中移除。 -
@AndrewThompson 谢谢!! ...而且它是如此简单,我有点傻,没有想到它大声笑
-
“我有点傻,没有想到它” 发生这种情况时也是如此(这种情况经常发生)。然后我咯咯笑了一会儿。这是编程乐趣的一部分。 ;)