I want to redraw a JPanel while my program is running. Here's a fragment of my code:

public class Graph extends JPanel{
public void redrawSomething()
{
	getGraphics().drawRect(15, 5, 20, 5);
	repaint();
}

I tried to call "redrawSomething" but nothing happend. How do I fix it? Is something wrong?

It's no good trying to draw things to the Graphics like that - Swing is in charge of drawing and will ignore/over-paint your drawing.
The correct way is to override the paintComponent(Graphics g) method to include your own drawing code. Swing will call this whenever it is necessary - eg because the window has been resized, or you have requested it by calling repaint();
Look at the second (Swing) part of this:
http://java.sun.com/products/jfc/tsc/articles/painting/

Try...

public void redrawSomething(Graphics G)
{
   G.setColor (Color.white);
   G.drawRect(15, 5, 20, 5);
}

Remember that people search these threads for answers, so perhaps you could just post quickly HOW you solved it, for the benefit of others.

I used hfx642 way:

public void redrawSomething(Graphics g)
{
   g.setColor (Color.white);
   g.drawRect(15, 5, 20, 5);
}

my class look like this:

class Graph extends JPanel{
boolean execute=false;
...

public void redrawSomething()
{
    execute=true;
    update(getGraphics());
}

private void redrawSomething(Graphics g)
{
   g.setColor (Color.white);
   g.drawRect(15, 5, 20, 5);
}

protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(execute)
            redrawSomething(g);
}
...

Edited 5 Years Ago by teo236: n/a

This question has already been answered. Start a new discussion instead.