java Java2d:JPanel 设置背景颜色不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2831206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java2d: JPanel set background color not working
提问by Boolean
I have the code shown below:
我有如下所示的代码:
public VizCanvas(){
{
this.setBackground(Color.black);
this.setSize(400,400);
}
}
It worked fine and displays the panel in black background. But when I implement the paint method, which does nothing, the color changes to default color i.e gray.
它工作正常并以黑色背景显示面板。但是当我实现什么都不做的paint方法时,颜色会变为默认颜色,即灰色。
I tried to set graphics.setColor() but it didn't help.
我试图设置 graphics.setColor() 但它没有帮助。
回答by Chris Dennett
You need to do a fill of the canvas to your background colour in the painting method. Something along the lines of:
您需要在绘画方法中将画布填充到您的背景颜色。类似的东西:
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
After that, draw whatever you need to. You could also try calling super.paint(g)in the paint method instead before doing anything.
之后,绘制任何你需要的东西。你也可以尝试super.paint(g)在做任何事情之前调用paint方法。
回答by camickr
Custom painting should be done by overriding the paintComponent() method, NOT the paint() method. Then all you do is invoke super.paintComponent() to get the background painted.
自定义绘画应该通过覆盖paintComponent() 方法而不是paint() 方法来完成。然后你要做的就是调用 super.paintComponent() 来绘制背景。
Setting the size of the component does nothing. The layout manager will override the size. You should be setting the preferred size or override the getPreferredSize() method.
设置组件的大小没有任何作用。布局管理器将覆盖大小。您应该设置首选大小或覆盖 getPreferredSize() 方法。
Read the Swing tutorialfor Swing basics. There are sections on "custom painting" and "using layout managers".
阅读Swing 教程以了解 Swing 基础知识。有关于“自定义绘画”和“使用布局管理器”的部分。

