简体   繁体   English

Java getContentPane()。setBackground()无法正常工作

[英]Java getContentPane().setBackground() not working

Im trying to encapsulate the GUI calls to a single class. 我试图将GUI调用封装为单个类。 My window appears but the background remains the default color instead of red. 我的窗口出现,但是背景仍然是默认颜色,而不是红色。

ChatProgram.java ChatProgram.java

package ChatPkg;

public class ChatProgram {

    /**
     * Launch the application.
     */
    public static void main(String[] args) {

        ChatWindow.initialize();
        ChatWindow.RunWindow();

    }

}

ChatWindow.java ChatWindow.java

package ChatPkg;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

public final class ChatWindow {

    static JFrame frame;

    /**
     * Create the application.
     */
    private ChatWindow() { }

    public static void RunWindow() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Initialize the contents of the frame.
     */
    public static void initialize() {
        frame = new JFrame("Chat program");
        frame.setBounds(100, 100, 450, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JCheckBox chckbxCvbc = new JCheckBox("cvbc");
        frame.getContentPane().add(chckbxCvbc);

        // Set background color
        frame.getContentPane().setBackground(Color.red);
    }

}

Yes i am new to Java and none of the google results solved my problem. 是的,我是Java的新手,而Google的结果都没有解决我的问题。

You should NOT add GUI components directly to the content pane of the JFrame . 应该直接添加GUI组件到的内容窗格中JFrame Also, you shouldn't modify its properties (like you tried changing the background). 另外,您不应修改其属性(就像您尝试更改背景一样)。

You always need a JPanel that acts as a container on which the graphical elements are added. 您始终需要一个充当容器的JPanel ,在其上添加图形元素。 Here is how you could write your initialize function: 这是编写初始化函数的方法:

public static void initialize() {
    frame = new JFrame("Chat program");
    frame.setBounds(100, 100, 450, 450);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();

    JCheckBox chckbxCvbc = new JCheckBox("cvbc");
    panel.add(chckbxCvbc);

    // Set background color and add panel to the Jframe
    panel.setBackground(Color.RED);
    frame.getContentPane().add(panel);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM