Java:我无法更改JButton的背景

3

大家好。我正在开发一个Java程序。我想改变JButton的背景色,但我无法更改它。当函数结束时,颜色没有任何变化。以下是我的代码:

public void initialization() {
        button = new JButton[size][size];
        mainPanel.setLayout(new GridLayout(0, size));
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                button[i][j] = new JButton();
                button[i][j].setBackground(Color.BLACK);
                //button[i][j].setVisible(true);
                //button[i][j].setEnabled(false);
                mainPanel.add(button[i][j]);

            }
        }
        mainPanel.updateUI();
        System.out.print("Button Finished\n");
    }

我希望有人能够帮助我。

这段内容与IT技术无关。
1个回答

8
试着在更改背景之前将其设置为不透明:
button[i][j].setOpaque(true);
button[i][j].setBackground(Color.BLACK);

是的!那就是关键!谢谢你!我会在8分钟内将其标记为正确答案。系统不允许我在8分钟内这样做。 - Yuhao_Zhu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接