• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

How to refresh JPanel automatically when internal state changed?

 
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.
 
author and iconoclast
Posts: 24203
43
Mac OS X Eclipse IDE Chrome
  • 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.
 
My, my, aren't you a big fella. Here, have a tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!