JPanel setBackground(Color.BLACK)什么都不做

Pri*_*alj 9 java swing background jpanel setbackground

我有下面的自定义JPanel,我已经使用Netbeans GUI构建器将其添加到我的框架中,但背景不会改变!我可以看到圆圈,用g.fillOval()绘图.怎么了?

public class Board extends JPanel{

    private Player player;

    public Board(){
        setOpaque(false);
        setBackground(Color.BLACK);  
    }

    public void paintComponent(Graphics g){  
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
    }

    public void updatePlayer(Player player){
        this.player=player;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*aux 15

你必须调用它super.paintComponent();,以允许Java API绘制原始背景.super指的是原始的JPanel代码.

public void paintComponent(Graphics g){
    super.paintComponent(g);

    g.setColor(Color.red);
    g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}
Run Code Online (Sandbox Code Playgroud)

  • @PrimožKralj:如果你很快得不到合适的答案,那么考虑创建和发布[SSCCE](http://sscce.org). (2认同)

Ste*_*fan 15

如果您的面板"不透明"(透明),您将看不到您的背景颜色.

  • +1,OP正在编写`setOpaque(false)`并且仍然希望颜色可见:( (8认同)