Search code examples
javaswingjpanelgraphics2d

Redrawing graphics in Java


I'm just getting into graphics in Java and I have a problem. I created a JFrame window (NetBeans Designer) with a JPanel panel and I drew some graphics on it. Then I added a JButton that changed a variable, which would change the X position of a square on JPanel.

On button press this code would execute:

drawObject.setX(150);
drawObject.repaint();

drawObject is an instance of this class:

public class sola extends JPanel {

    private int x = 10;

    @Override
    public void paintComponent(Graphics g){
        super.paintComponents(g);
        super.setBackground(Color.WHITE);

        g.setColor(Color.ORANGE);
        g.fill3DRect(x, 160, 100, 50, true);
    }

    public void setX(int xX){
        x = xX;
    }
}

Now, when I press the JButton, the rectangle does move to the new position, however it is still visible in the old position. Only when i resize the window does it refresh and the old rectangle disappears. How can i solve this problem, so that when i press the button, the rectangle is only visible in the new position?


Solution

  • It's

    super.paintComponent(g);
    

    not

    super.paintComponents(g);  // note the s at the edn
    

    Big difference between the two! The first one tells your JPanel to do all the housekeeping functions normally performed by the paintComponent method, including repainting the background (key for your project). The second, the one your calling doesn't do any of the above functionality. So my advice is to get rid of the trailing s in your super call.