【问题标题】:Buttons change color, but I need them to stop when I click them按钮改变颜色,但是当我点击它们时我需要它们停止
【发布时间】: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 exampleShort, Self Contained, Correct Example。 2)不要阻塞EDT(事件调度线程)。发生这种情况时,GUI 将“冻结”。有关详细信息和修复,请参阅Concurrency in Swing。 3) 若要从进一步的颜色变化中移除(停止)按钮,请在执行操作时将其从buttons 数组列表中移除。
  • @AndrewThompson 谢谢!! ...而且它是如此简单,我有点傻,没有想到它大声笑
  • “我有点傻,没有想到它” 发生这种情况时也是如此(这种情况经常发生)。然后我咯咯笑了一会儿。这是编程乐趣的一部分。 ;)

标签: java swing awt


【解决方案1】:

若要从进一步的颜色变化中移除(停止)按钮,请在执行操作时将其从buttons 数组列表中移除。

【讨论】:

    【解决方案2】:

    我会创建一个包含 8 个布尔值的数组来跟踪按钮。并在此处检查按钮是否应更改其颜色:

    for (int i = 0; i < 8; ++i){
      if(!pressedArr[i]){
        button.setBackground(getColor());//change colors
      } 
    }
    

    你还需要跟踪所有八个值,当它们都是true时,就跳出while循环

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 1970-01-01
      • 2022-08-10
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多