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?

re validate before repaint.
Google some example you will get it.

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/

Member Avatar for hfx642

Try...

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

Remember java coding conventions?
G vs g for variable names

thanks a lot. problem solved

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);
}
...
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.