Redrawing Graphics in Java

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

On, click this code:

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 JButton, the rectangle moves to a new position, however it is still displayed 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 visible only in the new position?

+3
source share
3 answers

it

super.paintComponent(g);

not

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

! JPanel , paintComponent, ( ). , , , . , .

+3

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.

redraw()

+1

repaint() tis.

paintComponent() . . , .

I recommend creating your own component for your rectangles. (You can go from Component), then you can override the method of paintComponentthese classes, as it was in your panel. Because the group must act as a component of the container. Not like drawing the rectangles themselves.

Be aware, add instances of these components to a regular JPanel. Then it should be updated as expected.

+1
source

All Articles