• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

time dependent events

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Evacuate the building! Here, take this tiny ad with you:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic