更改框架内面板的背景颜色

Changing the background color of a panel inside a frame

正如标题所说,我正在尝试在框架内设置面板的背景颜色,以便它们都具有不同的颜色。到目前为止我尝试的是单独或同时使用 setBackground 方法,我得到的结果总是只显示一种颜色,这很奇怪,因为内框不应该改变外框frame的设置对吧?

代码示例:

public class frameStuff{

    private JFrame frame;
    private frame1 in_frame;

    @SuppressWarnings("serial")
    class frame1 extends JPanel  {
        frame1(){
            super();
        }

        public void paint(Graphics g){

        }
    }

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

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

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 500, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
//      frame.getContentPane().setBackground(Color.GRAY);/*if this line wasn't a comment then everything would be grey instead of white as it's now.

        in_frame = new frame1();
        in_frame.setBounds(100, 100, 350, 220);
        in_frame.setBackground(Color.BLUE);
        in_frame.setVisible(true);//this doesn't seem to matter whatever the case
        frame.getContentPane().add(in_frame);

    }
}
class frame1 extends JPanel  {
    frame1(){
        super();
    }

    public void paint(Graphics g){
    }
}

应该是:

// Should be called a Panel (since it is one) and use correct case
class Panel1 extends JPanel  {
    Panel1(){
        super();
    }

    // The method to override for custom painting in ANY JComponent
    @Override // handy to check we got the method signature right
    public void paintComponent(Graphics g){
        // paints the background, borders etc.
        super.paintComponent(g);
        // all custom drawing AFTER this line..
    }
}

It seems like adding this one line super.paint(g); to the paint method solves the problem here, do you still suggest doing it as you mentioned?

是的。

Is it faster this way?

是的。如果只是因为您仍然需要将代码中的方法和 recompile/build 项目更改为可以可靠呈现的东西,而没有奇怪的工件。现在,这可能对你来说是正确的,但这纯粹是偶然的。