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

我有以下的自定义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; } } 

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

你必须调用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()); } 

我只是尝试了一个简单的实现,它只是工作:

 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; } } 
 setOpaque(false); 

变成

 setOpaque(true); 

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

 public Board(){ JPanel pane = new JPanel(); pane.setBackground(Color.ORANGE);// sets the background to orange } 

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

1)首先设置背景颜色

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

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

另一个有用的提示:如果你想在特定的区域(比如掩码或“洞”)中绘制,请调用具有“孔”形状(任何形状)的图形的setClip()方法,然后调用Clear()方法(之前应将背景设置为“孔”颜色)。

你可以通过调用方法clip()(你想要的任何时候)来制作更复杂的剪辑区域。在调用方法setClip()以获得裁剪形状的交叉点之后。

我找不到任何关于剪切区域的联合或反转的方法,只有交叉点,太糟糕……

希望能帮助到你