JPanel setBackground(Color.BLACK) does nothing
110,407
Solution 1
If your panel is 'not opaque' (transparent) you wont see your background color.
Solution 2
You have to call the super.paintComponent();
as well, to allow the Java API draw the original background. The super refers to the original JPanel code.
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}
Solution 3
You need to create a new Jpanel object in the Board constructor. for example
public Board(){
JPanel pane = new JPanel();
pane.setBackground(Color.ORANGE);// sets the background to orange
}
Solution 4
setOpaque(false);
CHANGED to
setOpaque(true);
Solution 5
I just tried a bare-bones implementation and it just works:
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;
}
}
Author by
c0dehunter
Updated on July 05, 2022Comments
-
c0dehunter almost 2 years
I have the folowing custom JPanel and I have aded it to my frame using Netbeans GUI builder but the background won't change! I can see the circle, drawing with g.fillOval(). What's wrong?
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; } }