Squeazer
Squeazer

Reputation: 1254

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?

Upvotes: 3

Views: 17325

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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.

Upvotes: 3

Chris
Chris

Reputation: 7855

You could use repaint() method to do tis.

If you use the paintComponent() on the panel. You should IMHO take care of the painting in the whole panel. There is no code in your example which takes care about deleting the old painted rectangles.

What i recommend is creating an own Component for your rectangles. (You could extend from Component) then you can override the paintComponent method of these classes as you did in your panel. Because the Panel should act as a container component. Not as drawing the rectangles itsself.

Know add instances of these components to a normal JPanel. This should then update as expected.

Upvotes: 1

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

You can use the following methods from JComponent: ( http://download.oracle.com/javase/6/docs/api/javax/swing/JComponent.html )

void    repaint(long tm, int x, int y, int width, int height)
 Adds the specified region to the dirty region list if the component is showing.
void    repaint(Rectangle r)
 Adds the specified region to the dirty region list if the component is showing.

You can call those before redraw()

Upvotes: 1

Related Questions