简体   繁体   English

Java2d:JPanel设置背景色不起作用

[英]Java2d: JPanel set background color not working

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 ie gray. 但是当我实现不执行任何操作的paint方法时,颜色将更改为默认颜色,即灰色。

I tried to set graphics.setColor() but it didn't help. 我试图设置graphics.setColor(),但没有帮助。

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. 您还可以尝试在执行任何操作之前先在​​paint方法中调用super.paint(g)

Custom painting should be done by overriding the paintComponent() method, NOT the paint() method. 自定义绘画应通过重写paintComponent()方法而不是paint()方法来完成。 Then all you do is invoke super.paintComponent() to get the background painted. 然后,您要做的就是调用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 tutorial for Swing basics. 阅读有关Swing基础知识的Swing教程 There are sections on "custom painting" and "using layout managers". 有关于“自定义绘画”和“使用布局管理器”的部分。

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

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