user3369008
user3369008

Reputation: 101

paintComponent does not work on JPanel

so I have a Board class that extends JPanel and method write that when called saves some coordinates and calls repaint. However, the effect of repaint is not displayed on screen. When I tried to add JLabel with redbackground to the panel it showed up, so the panel is showing, it's just that repaint does not work.

public int x, y;
public JPanel panel = new JPanel();
private int xx,yy;
private Color c;

public Board(int x, int y, int wolfNumber, int hareNumber){
    this.x=x;
    this.y=y;

    wolvesCoords = new int[wolfNumber][2];
    haresCoords = new int[hareNumber][2];
    setLayout(new GridLayout());

    add(panel);
}

public synchronized void write(int xx, int yy, Color c){
        this.xx = xx;
        this.yy = yy;
        this.c = c;

        repaint();
}

@Override 
protected void paintComponent(Graphics g) {
        int width=panel.getWidth()/x;
        int height=panel.getHeight()/y;


        g.setColor(c);

        g.drawRect(xx*width, yy*height, width, height);
        g.fillRect(xx*width, yy*height, width, height);
    super.paintComponent(g);
}   

Upvotes: 1

Views: 1300

Answers (2)

Braj
Braj

Reputation: 46841

Override paintComponent for instance member panel rather then Board JPanel class itself.

panel = new JPanel() {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        ...// your code here
    }
};

Why Board class is extending JPanel?

Try to use design pattern such as Favor Composition over Inheritance

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347184

Call super.paintComponent first

One of the jobs of paintComponet us to fill the Graphics context with the components background color, this is done to ensure what ever was painted to the a Graphics context before is "cleaned" off

Take a look at Painting in AWT and Swingfor more details

Upvotes: 3

Related Questions