954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Graphics

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?

teo236
Junior Poster in Training
73 posts since Jul 2011
Reputation Points: 20
Solved Threads: 10
 

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

Majestics
Practically a Master Poster
621 posts since Jul 2007
Reputation Points: 199
Solved Threads: 49
 

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/

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

Try...

public void redrawSomething(Graphics G)
{
   G.setColor (Color.white);
   G.drawRect(15, 5, 20, 5);
}
hfx642
Posting Pro
515 posts since Nov 2009
Reputation Points: 248
Solved Threads: 105
 

Remember java coding conventions?
G vs g for variable names

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

thanks a lot. problem solved

teo236
Junior Poster in Training
73 posts since Jul 2011
Reputation Points: 20
Solved Threads: 10
 

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

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

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);
}
...
teo236
Junior Poster in Training
73 posts since Jul 2011
Reputation Points: 20
Solved Threads: 10
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: