This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

time dependent events  RSS feed

 
Peter Keila
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I want to do a sequential event chain in a Java Gui application.
As an example iIwant to change the name of a button after every second, so here it is: first wait a second then change name in "cat", then wait a minute and change name into "get".
The method um() should do this.
The strange thing is:
If i start um() from method set(), everything works fine .
If i start um() from the action performed method, it first does the waiting, and then the name gets directly to get.

Heres the code:

import java.awt.event.*;
import javax.swing.*;

public class pauser implements ActionListener {

JFrame frame = new JFrame();
JButton button = new JButton("hat");

public void set(){
frame.setSize(401,400);
frame.setVisible(true);
frame.add(button);
button.setEnabled(true);
button.addActionListener(this);
frame.setVisible(true);
um();
}

public void actionPerformed(ActionEvent event){
um();
}

void um(){
try{Thread.sleep(1000);}catch(Exception e1){}
button.setText("cat");
try{Thread.sleep(1000);}catch(Exception e1){}
button.setText("get");
}

public static void main(String[] args) {
new pauser().set();
}
}

Anyone who could help me out
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read This Tutorial on threads with Swing.

Basically, if you use the ActionPerformed method to call um() it is occurring in the Event Dispatch Thread, which is the same Thread used for painting the GUI. So when you try to set the value, then force the Event Thread to sleep for a second you are preventing the name you set from getting displayed.

You should basically have two Threads, one that does the sleeping and one that does name setting. Some classes that you can use to help do what you want would be The Swing Timer or perhaps the SwingWorker.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!