• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to refresh JPanel automatically when internal state changed?

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic