【问题标题】:Can't change background color of JFrame or JPanel无法更改 JFrame 或 JPanel 的背景颜色
【发布时间】:2017-02-23 12:18:27
【问题描述】:

我无法让 JPanel 改变颜色。我也无法让 JFrame 改变颜色。我在网上看过......我还有另一个程序,它具有几乎相同的代码来设置 JPanel 和 JFrame。我就是无法让它工作。

这是我的主要方法:

public static void main(String[] args){
    JFrame frame = new JFrame("title");
    frame.getContentPane().setBackground(Color.WHITE);
    Drawing drawing = new Drawing(2);
    drawing.setBackground(Color.CYAN);
    frame.add(drawing);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    ...

编辑:稍后在我的主要方法中是

    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

这里是 JPanel 的构造函数:

public class Drawing extends JPanel {
    // instance variables
    public Drawing(int n){
        setOpaque(true);
        setPreferredSize(new Dimension(300, 300));
        setBackground(Color.PINK);
        ...

并且背景颜色保持默认的灰色。

【问题讨论】:

标签: java swing colors jpanel


【解决方案1】:

我在使用 Eclipse 制作快速窗口构建器应用程序以及设置颜色时没有遇到任何问题。

我确实注意到的几件事是您使用frame.add(drawing) 而不是frame.getContentPane().add(drawing)
您也永远不会使用frame.setVisible(true) 设置可见的框架。

这是我使用的代码:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainWindow window = new MainWindow();
                window.frame.setVisible(true);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public MainWindow() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.getContentPane().setBackground(Color.GREEN);
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JPanel panel = new JPanel();
    panel.setBackground(Color.CYAN);
    panel.setBounds(10, 171, 128, 81);
    frame.getContentPane().add(panel);
}  

编辑:添加了代码工作的图片说明

【讨论】:

  • 我忘了提到我确实在方法后面设置了面板可见(编辑了我上面的帖子),但背景显示为灰色。
  • 我将在这里对你完全诚实,我不确定你为什么会遇到这个问题,我只是将你的代码复制到 eclipse 中,而不是以任何方式添加或编辑你的代码,我让它工作得很好,我添加了一张图片来说明这一点。我的猜测是你的一些其他代码把它搞砸了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2016-10-04
  • 2014-09-25
相关资源
最近更新 更多