Updating text displayed in a Swing Application
This was posted in a private message to me, and I am posting it instead in the forum as this type of discussion should be made public
Quote:
Originally Posted by princehektor
Hey ,
I'm trying to a develop a swing application. I am facing a problem when i attempt to update the value of a text area.
i have the text area called "mytextarea1" added to a panel which is added to a frame .I have a button "button_start" which should start the updating of the text area according to the function "startRunning".
The problem am i facing is that i can only see the value 1 and then finally 6.The other values are not being populated.
Code:
***************************************************************
public class my class implements ActionListener{
public int x;
JFrame myframe=new JFrame("sample");
JPanel mypanel=new JPanel(new FlowLayout());
JTextArea mytextarea1=new JTextArea(1,5);
JButton button_start= new JButton("Start");
.....
public void uiFunction() /* i'm calling this function from the main method */
{
.....
button_start.addActionListener(this);
int count=0;
mytextarea1.setText(Integer.toString(count));
}
@Override
public void actionPerformed(ActionEvent e)
{
int count=0;
Object source=e.getSource();
if(source==button_start)
{
startRunning(count);
}
}
public void startRunning(int x)
{
if(func1()==1)
{
x++;
mytextarea1.setText(Integer.toString(x));
System.out.println("x ="+x);
if(x==6)
return;
startRunning(x);
}
}
Quote:
Could u please point out the mistake?
Thanks in advance.
Re: Updating text displayed in a Swing Application
There is no "mistake" in x goes through all numbers up to 6, but it does so so quickly you don't see the interim result. Also you're using recursion (a method calling itself) where it isn't necessary and is potentially dangerous. I suggest that instead you use a Swing Timer so as to set a delay between changes in x in a thread-safe way. Google for the tutorials on how to use Swing Timers as this will show you all you need to know.
Also, you'll want to leave "urgent" out of all your posts here as it will have the opposite effect intended. Folks look on that as you thinking that your post is more important than any others, and it may make them not want to help you. And really your urgency is your problem only, not ours.
Luck.