mounika
mounika

Reputation: 11

Using Threads to perform operations on same jframe

i need to develop java code to have JFrame with a text filed and button.Using Threads,i need to update time for every one minute in the title bar of JFrame.Using Another Thread i need to display textbox value in the console when a button is clicked.I have code for performing both operations (updating time for every min and getting text box value)but i dont know how to add two threads in same class.if anyone knows pls help me out

Upvotes: 0

Views: 304

Answers (1)

matt forsythe
matt forsythe

Reputation: 3912

What you are asking is a dangerous thing to do in Swing. Swing components are not thread-safe and should only be updated from the Event Dispatching Thread (also known as the EDT or Swing Thread). To do this, Swing has utility methods such as SwingUtilities.invokeLater(Runnable) which will execute the code in the Runnable (at some point in the future) on the EDT. The idea is that you place your code to do Swing-things (like update the Title of the JFrame with the time) inside of a separate Runnable and pass it to invokeLater().

To do this, you can create an anonymous Runnable class:

Runnable updateJFrame = new Runnable () {
    public void run () {
        myJFrame.setTitle("My New Title");
    }
};

SwingUtilities.invokeLater(updateJFrame);

Using invokeLater() also ensures that the components get refreshed/repainted properly after they have been updated. (The behavior you are seeing when using statics may actually be a refresh/repaint issue.) The moral of this story is that if you manipulate Swing components on a non-EDT thread, all bets are off.

Upvotes: 1

Related Questions