Java getContentPane()。setBackground()不起作用

时间:2017-03-30 20:33:29

标签: java swing

我试图将GUI调用封装到单个类中。我的窗口出现,但背景仍然是默认颜色而不是红色。

ChatProgram.java

package ChatPkg;

public class ChatProgram {

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

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

    }

}

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);
    }

}

是的,我是Java的新手,并没有谷歌搜索结果解决了我的问题。

1 个答案:

答案 0 :(得分:0)

您不应将GUI组件直接添加到JFrame的内容窗格中。此外,您不应该修改其属性(就像您尝试更改背景)。 您总是需要一个JPanel作为容器,在其上添加图形元素。以下是编写初始化函数的方法: public static void initialize(){     frame = new JFrame(" Chat program");     frame.setBounds(100,100,450,450);     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     JPanel面板=新JPanel();     JCheckBox chckbxCvbc =新的JCheckBox(" cvbc");     panel.add(chckbxCvbc);     //设置背景颜色并将面板添加到Jframe     panel.setBackground(Color.RED);     。frame.getContentPane()添加(面板); }
相关问题