How to pass variable back from thread for animation
Hello how do I pass a variable (ScrollX) back from a thread to animate a ball bouncing around on a Jpanel... The following code has everything working except I cannot figure out how to pass the position variable back to paintcomponent so when i repaint it does not move...
Also the only way I could get the paintcomponent to work on the jpanel was to call it from the jpanel constructor is there some other way to do this more efficiently?
Thanks for the Help
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class UserInterfaceSetup
{ int ScrollX;
JFrame frame = new JFrame("UserInterface");
JPanel Panel1 = new JPanel(){
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.orange);
g.fillOval(ScrollX,200,20,20);
}
};
public void ui()
{
Panel1.setLayout(null);
frame.setVisible(true);
frame.setSize(640,480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(Panel1);
UpdatePlot UpdatePlot1 = new UpdatePlot();
new Thread(UpdatePlot1).start();
}
class UpdatePlot extends JPanel implements Runnable
{
public UpdatePlot(){}
public void run()
{
while(true)
{
System.out.println(ScrollX);
ScrollX = (int) (Math.random() * 300);
repaint();
try {
Thread.sleep(1000);
} catch (Exception ex) {}
}
}
}
}
public class UserInterface extends UserInterfaceSetup
{
public static void main(String[] args)
{
UserInterfaceSetup n = new UserInterfaceSetup();
n.ui();
}
}
Thanks again for the help!