Skip to content
Advertisement

Moving code from ActionListener to main()

PROBLEM:

I have following code for the java.awt.Button :

JavaScript

I need to move the code inside btn.addActionListener to the public static void main(String[] args), something like below (in pseudo code):

JavaScript

RELEVANT INFORMATION :

I am aware that there are better solutions for GUI development, but I am restricted to using AWT for UI.

I have no power to change the above, nor can I provide details about the real code due to legal restrictions.

To remedy above, I am submitting the below MVCE. Please base your answers on it:

JavaScript

MY EFFORTS TO SOLVE THIS:

I have used Google extensively, and was able to find some useful links.

  1. UI will run in the separate thread, which will make it responsive (I do not know how to join() it properly, though).
  2. For signaling mechanism, wait() and notify() seem like the right way to go.
  3. To set Button’s text, I can use EventQueue.InvokeAndWait.
  4. To get Button’s text, I do not know what to do, but I have an ugly workaround.

Below is the modified MVCE :

JavaScript

Advertisement

Answer

As I understand your question, you want the main thread to be notified when the [AWT] button is clicked and upon receipt of that notification, you want to change the text of that button’s label.

I started with the code from your modified minimal-reproducible-example that you posted in your question.

Here is my code with explanatory notes after it.

JavaScript

In order for the GUI thread to notify the main thread, I agree with you that wait() and notifyAll() is the mechanism to use. I use notifyAll() rather than notify() to make sure that all the waiting threads are notified.

I use a shared variable btnTxt to transfer the text of the button’s label between the GUI thread and the main thread.

By default, the action command of the ActionEvent is the text of the [AWT] button’s label. Hence the use of method getActionCommand() in my ActionListener implementation.

All changes to the GUI must be executed on the GUI thread, so after creating the new text for the button’s label in the main thread, I use method invokeLater() of class java.awt.EventQueue to actually change the button’s label text.

You should be able to copy the above code as is, compile it and run it.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement