在JPanel上用Java设置背景色不起作用

dauxcl2d  于 2023-04-04  发布在  Java
关注(0)|答案(4)|浏览(262)

我正在开发一个“paint-like”应用程序(一个小绘图软件)来熟悉Java 2D组件。我有一个JFrame,它的ContentPane是继承自JPanel的类的示例。我想将背景颜色设置为白色,但它仍保持其默认颜色... ContentPane对应的类名是Container。下面是一个简化的代码:

public class Container extends JPanel {

    public Container() {
        super();
        this.setBackground(Color.WHITE);
    }
}

JFrame构造函数包含以下行:

this.setContentPane(mainContainer);

我错过什么了吗?
谢谢

chhkpiq4

chhkpiq41#

这个可以解决

public class Container extends JPanel
{
    public Container() 
    {
        super();
        this.setOpaque(true);
        this.setBackground(Color.WHITE);
    }
}
7d7tgy0s

7d7tgy0s2#

对于某些组件,默认情况下背景是关闭的。背景颜色仅应用于不透明的小部件。为小部件层次结构中应绘制其背景的所有组件调用以下方法:

component.setOpaque(true);
pinkon5k

pinkon5k3#

我也有这个问题,只有这样才能解决,这正是OP的建议。

// Only this works for me
this.setBackground(Color.blue);

示例类的完整代码在这里(只是为了显示我试图放置/设置setBackground()的位置;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class CircleDraw extends JFrame {
    Float diameter = 150f;

    public CircleDraw() {
        super("Circle Draw");
        this.setSize(300, 300);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.add(new CirclePanel(diameter));
        this.setVisible(true);

        // Only this works for me
        this.setBackground(Color.blue);
    }

    public static void main(String[] args) {
        new CircleDraw();
    }
}

class CirclePanel extends JPanel {

    Float diameter;

    public CirclePanel(Float diameter) {
        super();
        // this.setOpaque(true);
        // this.setBackground(Color.WHITE);
        this.diameter = diameter;
    }

    @Override
    public void paintComponent(Graphics g) {

        int panelWidth = this.getSize().width;
        int panelHeight = this.getSize().height;

        setPreferredSize(new Dimension(300, 300));
        Graphics2D comp2D = (Graphics2D) g;
        comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        comp2D.setStroke(new BasicStroke(1f));
        // comp2D.setBackground(Color.white);
        comp2D.setPaint(Color.white);

        Ellipse2D.Float e1 = new Ellipse2D.Float((panelWidth / 2) - (diameter / 2), (panelHeight / 2) - (diameter / 2), diameter, diameter);
        comp2D.draw(e1);
    }
}
eyh26e7m

eyh26e7m4#

你需要在覆盖函数中包含超级函数。IE

protected void paintComponent(Graphics g){
    super.paintComponent(g); // this sets the background normaly
    g.setColor(Color.BLACK);
    g.drawLine(0,0,getWidth(),getHeight());
}

相关问题