【问题标题】:JButton color not changingJButton颜色不变
【发布时间】:2018-09-29 04:11:30
【问题描述】:

我正在尝试创建一个非常基本的 Java GUI 程序来解决 Boggle 板问题。
它使用递归 DFS。我想要发生的是按钮的背景颜色(我使用按钮只是因为它们已经是正方形)从黄色变为红色,因为字母被“标记”并在“未标记”时返回黄色。
如果我注释掉将其重新充电为黄色的最后一行,以及使用 Thread.sleep() 延迟程序的方法,它会按预期工作,将它们全部保留为红色,但如果我只取消注释延迟方法,它确实不实时更新,程序运行结束后所有背景都变为红色。
如果我取消注释将其变回黄色的行,它会一直保持黄色。

我不知道如何让按钮实时切换为红色和返回黄色。

if(r+1 != bBoard.length && c+1 != bBoard.length && !bBoard[r+1][c+1].equals(""))
    {
        String temp = bBoard[r][c];
        bBoard[r][c] = "";
        boardLabel[r][c].setBackground(Color.RED);
        if(dictionary.contains(word) && word.length() > 2)
        {
            wordList.add(word);
            delayProgram();

        }
        depthFirstSearch(bBoard, r+1, c+1, word);
        bBoard[r][c] = temp;
        boardLabel[r][c].setBackground(Color.YELLOW);
    }

【问题讨论】:

  • “实时”表示更改按钮颜色的代码存在于事件侦听器(例如 ActionListener)中。我们不知道这是否基于此代码 sn-p。此外,永远不要让 GUI 线程进入睡眠状态。如果您在 Swing GUI 中需要延迟,请改用 Swing Timer
  • @HovercraftFullOfEels 代码不在动作监听器中,按钮实际上从未用作按钮,我只是为了格式化而制作按钮。颜色在由不同按钮调用的循环内更改,其颜色永远不会改变
  • 那么这段代码是在创建对象时调用的吗?根据我们对您的问题和代码的有限看法,很难说发生了什么,您需要考虑edit提出您的问题并向我们展示更相关的代码作为代码格式的文本,确切地说是minimal reproducible example (请阅读链接)。
  • 所以如果我理解正确的话,你有一堆(表)黄色按钮。您循环浏览它们并将它们的颜色更改为红色一段时间,然后再变回黄色并移动到下一个按钮,对吗?
  • @MatheM 是的。它正在模拟一个boggle board,它进行dfs搜索,它将从左上角开始,将第一个字母添加到字符串中,然后通过将其添加到相同的字符串并检查树集来检查其右侧的字母字典单词。我希望字符串当前包含的字母为红色,然后在不再使用时变回黄色。但它们始终保持黄色。我将所有按钮都更改为标签,但仍然得到相同的行为。

标签: java swing colors jbutton


【解决方案1】:

默认情况下,您的应用程序启动单线程并在该线程上执行所有计算。当你改变组件的颜色时,它只会在程序有空闲时间做的时候重新绘制,但程序永远没有空闲时间,因为计算还在继续。

你需要做的是把这个循环中的代码放到另一个线程,然后从这个第二个线程更新 GUI。

这是一个可以帮助您入门的小示例。

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ColorfulButtons extends JFrame {

    private JLabel[] labels = new JLabel[5];

    // start the application, this starts the original thread
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ColorfulButtons frame = new ColorfulButtons();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public ColorfulButtons() {
        // create your gui
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        JPanel contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(new GridLayout(1, 0, 0, 0));

        for (int i = 0; i < 5; i++) {
            JLabel lbl = new JLabel("TEXT");
            add(lbl);
            labels[i] = lbl;
        }

        // start the color changing thread
        new Thread(new Runnable() {

            public void run() {
                doTheThing();
            }
            // give it a name for debugging
        }, "DoTheThingThread").start();
    }

    private void doTheThing() {
        int index = 0;
        while (true) {
            // put label in final variable so I can use it inside anonymous classes
            final JLabel lbl = labels[index];

            // make label yellow on Event Dispatch Thread
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    lbl.setForeground(Color.YELLOW);
                }
            });

            // pause to give the gui time to redraw and process events 
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // make label red on Event Dispatch Thread
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    lbl.setForeground(Color.RED);
                }
            });

            // increment or reset index
            if (index < 5 - 1)
                index++;
            else
                index = 0;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 2019-04-22
    • 2018-09-28
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多