File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes How to refresh JPanel automatically when internal state changed? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to refresh JPanel automatically when internal state changed?" Watch "How to refresh JPanel automatically when internal state changed?" New topic
Author

How to refresh JPanel automatically when internal state changed?

Yijun Xie
Greenhorn

Joined: Apr 22, 2002
Posts: 14
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

Joined: Jul 08, 2003
Posts: 24183
    
  34


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.


[Jess in Action][AskingGoodQuestions]
Yijun Xie
Greenhorn

Joined: Apr 22, 2002
Posts: 14
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to refresh JPanel automatically when internal state changed?
 
Similar Threads
fluctuation
Simple JPanel question
string concatenation
Problem with custom painting and multiple JPanel
problem in creating more than one objects