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;
    }
}
4

6 回答 6

16

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

于 2012-04-14T00:28:34.537 回答
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());
}
于 2012-04-13T21:16:42.990 回答
4

您需要在 Board 构造函数中创建一个新的 Jpanel 对象。例如

public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 
于 2014-09-02T22:23:47.470 回答
4
setOpaque(false); 

变成

setOpaque(true);
于 2014-09-09T18:09:44.270 回答
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;
    }
}
于 2012-04-14T00:45:21.880 回答
0

为了将背景完全设置为给定的颜色:

1)首先设置背景颜色

2)调用方法“Clear(0,0,this.getWidth(),this.getHeight())”(组件绘制区域的宽度和高度)

我认为这是设置背景的基本程序......我遇到了同样的问题。

另一个有用的提示:如果你想绘制但不在特定区域(类似于蒙版或“洞”),请使用“洞”形状(任何形状)调用图形的 setClip() 方法,然后调用Clear() 方法(背景应事先设置为“孔”颜色)。

您可以通过在调用方法 setClip() 之后调用方法 clip()(任何时候)来制作更复杂的剪辑区域,以具有剪辑形状的交叉点。

我没有找到任何合并或反转剪辑区域的方法,只有交叉点,太糟糕了......

希望能帮助到你

于 2016-02-28T17:24:53.533 回答