简体   繁体   English

如何使用 Java AWT setBackground

[英]How to use Java AWT setBackground

This is some code to create a basic java window:这是一些用于创建基本 Java 窗口的代码:

JPanel pane = new JPanel();
gui(String title){
    super(title);
    setBounds(100,100,500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container con = this.getContentPane();
*   con.setBackground(new Color(0,0,0));
    con.add(pane);
    setVisible(true);
}

The line marked with a star (*) is meant to make the window's background color black (0,0,0).标有星号 (*) 的行旨在使窗口的背景颜色为黑色 (0,0,0)。 However, that line seems to do nothing.然而,那条线似乎什么也没做。 (I have tried using pane.setBackground here, but that made no diffference.) (我在这里尝试过使用pane.setBackground ,但这并没有什么区别。)

How do I change the background color?如何更改背景颜色?

You have added the JPanel over the JFrame which completely blocks out the underlying container on which you have set the color.您已经在JFrame添加了JPanel ,它完全屏蔽了您设置颜色的底层容器。

You could do this instead:你可以这样做:

public Gui(String title) {
   super(title);
   JPanel pane = new JPanel();
   setBounds(100, 100, 500, 500);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container con = this.getContentPane();
   pane.setBackground(new Color(0, 0, 0));
   con.add(pane);
   setVisible(true);
}

You can't set the background color for a JFrame's content pane.您不能为 JFrame 的内容窗格设置背景颜色。 By that I meant:我的意思是:

 JFrame f = new JFrame() ;
 f.setBackground(Color.RED) ;

What you should do however is create a JPanel that will act as your background and set its color like so:但是,您应该做的是创建一个 JPanel,它将充当您的背景并像这样设置其颜色:

backgroundPanel.setBackground(Color.RED);

Jframe f =new Jframe();
f.setBackground(Color.red);

This may also solve the Problem in hand.这也可以解决手头的问题。

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

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