Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to refresh JPanel automatically when internal state changed?

 
Yijun Xie
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, everybody.
As I know, system will call paintComponent() when frame is resized. But I want the JPanel to refresh itself automatically when some other object's state is changed. How can I? Following is my code:
---------------------------------------------------
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Graphics;
public class MyPanel extends JPanel{
Radius radius;
public void paintComponent(Graphics g){
g.drawOval(0,0,radius.getR(),radius.getR());
}
public MyPanel(Radius radius){
this.radius = radius;
}

public static void main(String [] args){
JFrame frame = new JFrame("Test");
Radius radius = new Radius();
MyPanel myPanel = new MyPanel(radius);
frame.getContentPane() .add(myPanel);
frame.setSize(600,600);
frame.setVisible(true);
radius.growing();//line 21
}
}
class Radius {
private int r=50;

public void growing(){
while (true){
r++;
if ( r>500){
r = 50;
}
}
}

public int getR(){
return r;
}
}
------------------------------------------------
I expect myPanel to refresh when the radius change its state, but it didn't.
How can I? BTW, I don't want to call repaint() inside growing() method.
Thank you in advance.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

BTW, I don't want to call repaint() inside growing() method.

Well, that would be the way to do it. Why do you have this restriction? Note that repaint() doesn't actually do the painting; it just sends a message that painting is needed. Multiple repaint calls don't necessarily lead to multiple paintComponent() calls.
 
Yijun Xie
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ernest. Because If Radius want to call repaint() isnide growing(), then it has to have a refrence to myPanel object. But sometimes it can't have such a reference.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic