JPanel setBackground(Color.BLACK) 不起作用。

12

我有以下自定义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;
    }
}
6个回答

16
如果您的面板是“非不透明”的(透明的),您将无法看到您的背景颜色。

只有当组件是不透明的时候,才会使用背景颜色...—setBackground() - trashgod
10
+1,OP正在编写setOpaque(false)但仍然希望颜色可见:( - nIcE cOw

15

您还需要调用super.paintComponent();,以允许Java API绘制原始背景。 超级引用的是原始JPanel代码。

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

    g.setColor(Color.red);
    g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}

我之前尝试过(在谷歌搜索后找到的),但它并没有解决问题 :( - c0dehunter
我不确定,但我认为面板应该是不透明的。 - Martijn Courteaux
2
@PrimožKralj:如果您很快没有得到满意的回答,那么请考虑创建并发布一个SSCCE - Hovercraft Full Of Eels

4
在Board构造函数中需要创建一个新的JPanel对象,例如:
public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 

4
setOpaque(false); 

更改为

setOpaque(true);

也许您可以简要解释一下帖子中代码的问题,然后介绍一下您的解决方案。谢谢! - Olimpiu POP

3

我刚刚尝试了一个简化版实现,它完美运行:

public class Test {

    public static void main(String[] args) {
            JFrame frame = new JFrame("Hello");
            frame.setPreferredSize(new Dimension(200, 200));
            frame.add(new Board());
            frame.pack();
            frame.setVisible(true);
    }
}

public class Board extends JPanel {

    private Player player = new Player();

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

    public void paintComponent(Graphics g){  
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillOval(player.getCenter().x, player.getCenter().y,
             player.getRadius(), player.getRadius());
    } 
}

public class Player {

    private Point center = new Point(50, 50);

    public Point getCenter() {
        return center;
    }

    private int radius = 10;

    public int getRadius() {
        return radius;
    }
}

我正在使用Netbeans进行工作,所以这样做很困难,但尽管如此,我已经成功手动创建了我的Board()并将其手动添加到我的Frame中。我原以为可以使用集成的GUI构建器来处理我的面板,但是那样我无法更改此Board JPanel的大小(即使在代码中也不行,因为它是自动生成的,我无法访问它)。 - c0dehunter

0
为了完全将背景设置为给定的颜色:
1)先设置背景颜色
2)调用方法“Clear(0,0,this.getWidth(),this.getHeight())”(组件绘制区域的宽度和高度)
我认为这是设置背景的基本过程...我也遇到了同样的问题。
另一个有用的提示:如果您想要绘制但不在特定区域内(类似于蒙版或“孔洞”),请使用图形的setClip()方法调用“孔洞”形状(任何形状),然后调用Clear()方法(背景应事先设置为“孔洞”颜色)。
您可以通过在调用setClip()方法之后多次调用clip()方法来创建更复杂的剪切区域,以便剪辑形状的交集。
我没有找到任何关于剪辑区域联合或反转的方法,只有交集,太糟糕了...
希望这可以帮助。

这个回答非常模糊,离题了,涉及到一些与 OP 无关的随意话题,而且第二步甚至不能编译,或者也许可以编译,但是没有给出该方法的上下文。至少,它不作为 JPanel 或 JFrame 的成员方法存在。请在您的帖子中提供更多上下文并简明扼要。 - kevr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接