Use swing in a different thread - java

I'm developing a cli-based custom web crawler in Java. Since it needs to have a user-friendly graphical interface for showing the result, I should add a swing frame to that involving some trees, labels, tables and so on.
That graphical interface is one of its switches, and must be started just in case user calls it. Thus, I have to start this interface in a new thread so that the application can proceed with other tasks and update components inside of GUI frame if needs.
My GUI class is some thing like:
public class Frame extends JFrame {
......
public static JLabel urlLabel;
......
public static void run() {
urlLabel = new JLabel();
urlLabel.setText("Test Url");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
.....
}
And, I fork it from my main class like this:
.....
if(cmd.gui){
Frame.run();
Frame.urlLabel.setText("New Url");
}
......
Unfortunately, the text of label doesn't change. I already tested repaint(), revalidate() and such other functions like these, but, nothing turned up.
I tested getText() in order to make sure it is possible to access urlLabel from main class, and it worked (I could retrieved text of label).
I was wondering how I can sort out this issue? (Basically, I need to start a swing frame in a different thread and control its components from the main thread)
Thanks in advance.

If you use invokeLater(), your Runnable will be started in the EventThread after the current operation in this thread is finished. If your label is not updated, it might be that your EventThread is busy doing something else - e.g. crawling the web.
You definitely need to make sure that your crawling work is done in another thread (start a new one, don't use the one that runs anyway, since this is most probably the EventThread). Then you might use invokeLater() in this other Thread to change the label in the EventThread.
Hint: You can check if you are in the EventThread by using SwingUtilities.isEventDispatchThread().
Remember that your data/models will be used by different threads and that this might cause problems when the data is changed in your worker thread while your GUI is trying to display it.

Thank you guys for helping.
Finally, I could overcome this obstacle by using SwingUtilities.invokeLater for updating the label's text.
I mention the approach here, since someone else might need it:
The main class:
public class Frame extends JFrame {
......
private static JLabel urlLabel;
......
public JLabel getU(){
return urlLabel;
}
public static void run() {
urlLabel = new JLabel();
urlLabel.setText("Test Url");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
.....
}
The GUI class:
if(cmd.gui){
Frame().run();
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
gui.getU().setText("New Url");
}
});
}
.....
Just a question about this manner:
Since I need to update some labels and tree nodes a couple of times during crawling, wanted to know if starting a new Runnable for each of those would be overload? If yes, how can I manage that?
---UPDATE---
According to the #xander's comment, it is possible to use lambda instead of Runnable. I think lambda doesn't have overload as much as a new object does.

Related

How to use a thread to run another JFrame while the main is still running

I have a jframe i want to display while my main frame is running. i want to pause my main code, until the user does the necessary actions on the other frame. I've read a lot of solutions but i need to see it done for my code to understand and grasp it fully. i do not want to use jdialog like I've seen listed as an answer before. My main goal is to understand better threading so that i can use what i learn in different cases.
With the code I've created, when running the thread, only just the frame loads, none of the other features are there on the frame. (the frame is simple it has a label, a list the user selects from, and a button to basically return the chosen list value.) its like the thread is cut off from completing or something.
here is my class calling the screen:
public class myThread implements Runnable {
String result = null;
public void run() {
MessageScreen ms = new MessageScreen();
ms.setVisible(true);
}
public String getResult() {
return result;
}
public void setResult(String AS) {
result = AS;
}
}
in my main code, a method is called that is returning a String[] value, with this method at some point i have the following code calling the new thread to get the value necessary to return in the original main method:
myThread mt = new myThread();
Thread t = new Thread(mt);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
myreturn = new String[] {"true", mt.getResult()};
without listing the whole code for the second frame, when the user presses the button, and at the end of the listener tied to the button press the i want to close the frame and return a string that was selected from the list:
jf.dispose();
myt.setResult(AdminSelection);
in the frame class, i have the following instance variables declared:
String AdminSelection = null;
myThread myt;
i hope this is enough information for someone to help me out and understand whats gone wrong here.
The function join() waits until the end of the run() method, when you do t.join(), your thread is already or almost ended. This is because in your run() method there is nothing that blocks the thread until the user has clicked the confirm button. And is better like this!
There is no sense to create a thread here, you should use a callback, or more generally in Java, a listener. You can take a look at Creating Custom Listeners.
But, especially if you want to pause your main code, you should use a (modal) JDialog which is made for this! Don't try to block the UI by yourself, you could block the UI thread (handled by Swing/AWT) by mistake. Creating a JDialog is better because everything is already made for this usage on the UI thread.
Also, you must know that create a Thread is really long, use a Thread when you really need it.

Ways of Implementing a GUI in Swing, Multithreading is a Concern

The goal is a GUI where in a window, having the play button pressed will release the GUI resources and start to run my game (the game is done outside of Swing, in LWJGL).
This is the first way I can see myself doing it. To me the safer option looks like this:
public static void main(String[] args) {
// setup gui objects
JFrame frame = ...;
frame.setVisible(true);
// wait for the play button to be pressed
synchronized(frame) {
frame.wait();
}
// free the gui objects, start the game
frame.dispose();
startGame();
}
// by the way, this method is called from the button's action listener
public void onPlayButtonPress(JFrame parent) {
// end the UI
synchronized(parent) {
parent.notify();
}
}
The reason this seems 'safe' to me is that the cleanup for the GUI and the game execution is done inside the main thread. Here is the second way I can see myself doing it, but I'm not sure how I feel about it:
public static void main(String[] args) {
// setup gui objects
JFrame frame = ...;
frame.setVisible(true);
}
public void onPlayButtonPress(JFrame parent) {
// free the gui objects
parent.dispose();
startGameInNewThread();
}
This second way of doing it seems more preferrable in that it is simpler, but I am worried of some problems coming up. For example:
Disposing the frame in the Event Dispatch Thread could mess things up?
Starting a new thread for the game while the main thread has already terminated?
So the reason I'm asking this question is because I'm looking for the best way to implement this, but I'm also kind of curious if and why any wierd things will happen if I implement my program the second way.

Updating GUI from a runnable

I'm building a Swing application and one part of the functionality should be to process and output some text visually and audibly (using Mary TTS). I need some advice on the best way for the GUI and text processing classes to communicate.
The GUI class is a subclass of JPanel. Within that I have a class implementing Runnable, called LineProcesser, which prepares the text to be dispatched to an audio player. I'm using a thread executor to keep this off the EDT (that may not be the best way but it seems to achieve the result I'm after).
My intention is for LineProcessor to run through all the text and update a JTextArea at the end of each line. Additionally it will need to halt and wait for user input at certain points. After the user input has been completed the GUI class should tell it to resume processing.
The following code illustrates what I currently have:
public class MyPanel extends JPanel {
ExecutorService lineExecutor = Executors.newSingleThreadExecutor();
Runnable lineProcessor = new LineProcessor();
public class LineProcessor implements Runnable {
private int currentLineNo = 0;
public LineProcessor() {
// ...
}
#Override
public void run() {
// call getText();
// call playAudio();
currentLineNo++;
}
}
}
private JButton statusLbl = new JLabel();
private JButton mainControlBtn = new JButton();
private void mainControlBtnActionPerformed(ActionEvent evt) {
if (mainControlBtn.getText().equals("Start")) {
lineExecutor.submit(lineProcessor);
mainControlBtn.setText("Running");
}
}
}
How can LineProcessor notify GUI components that they need to change and how can it be paused and restarted from within the GUI? I'm confused as to whether I need a Swing Worker, property/event listeners or something else? The examples I've read sort of make sense but I can't see how I can apply them to the code I have here.
All you need to do is wrap any Swing calls in a Runnable, and queue it on the EDT via SwingUtilities.invokeLater(myRunnable);. That's it. No need for a SwingWorker.
e.g.,
public class LineProcessor implements Runnable {
private int currentLineNo = 0;
Runnable LineProcessor = new LineProcessor(); // won't this cause infinite recursion?
public LineProcessor() {
// ...
}
#Override
public void run() {
// call getText();
// call playAudio();
currentLineNo++;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// *** Swing code can go here ***
}
});
}
}
You will have to use both SwingWorker and Event methodology.
Place your long running code in Swing Worker.
Create new property change Event, listener, manager
In your SwingWorker, when the change event occurs, call PropertyChangeManager to notify all the liseners.
All GUI components which wants to be notified with the event should register themselves with the PropertyChangeManager.
Your PropertyChangeManager will call customProperyChange method of the PropertyChangeListener and will pass the properyChangeEvent
What you are looking for is a SwingWorker. This class allows to perform the work on a worker thread, having periodical updates on the EDT, and in the end update the EDT as well.
Several examples are available on SO and in the Swing tutorials. Just a few links
The 'How to use progress bars tutorial', which happens to update a text area as well
The 'Concurrency in Swing' tutorial, a must-read if you start with SwingWorker
The SwingWorker javadoc
Reporting progress can be done with the publish method, these results will be passed to the process method in which you can update the UI. At the end, the done method is called allowing you to perform some final UI updates.
For the pause/restart functionality ... you can use an invokeAndWait in the doInBackground method with a blocking method call (for example showing a JOptionPane asking for user input). But if you start using invokeAndWait in the doInBackground it might be overkill to use the SwingWorker and you can simply opt for the approach #Hovercraft Full Of Eels suggested

How to keep one thread to call multiple JForms?

Let's say I have one thread running (I'm creating many instances of this thread), and inside that I instantiate a JForm. While being inside that JForm, I call another JForm. Think of it as a multiple step registration process. When I'm inside the second form, will the previously created thread still be inside the run()? Or is the new JForm creating a new thread? I want to keep the first thread alive and access a shared resource through out the lifetime of it.
class Form1 extends JForm{
public void jButton1ActionPerformed(..){
///show Form2
}
}
class A extends Thread{
public void run() {
//show Form1
}
}
class Main {
public static void main(String args[]){
new A().start();
new A().start();
new A().start();
}
Thanks.
When you create and run your A thread, you will simply show the Form and continue executing that Thread. Separately, on the single, dedicated Swing Thread (started automatically for you) the users click will be caught and handled, resulting in a call to jButton1ActionPerformed. That code block will execute inside the Swing thread.
Hope that helps. Note that you can name your threads and always use Thread.currentThread().getName() to help you understand further what is going on in your code.
If you want to create and show a Swing component from within a non-EDT thread, you must place the Swing code in a Runnable and queue it on the event thread like so:
class A extends Thread{
public void run() {
//show Form1
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Form1 form1 = new Form1();
form1.setVisible(true);
}
});
}
}
So regardless of how many "A" objects you create, and thus separate new threads you create, all Swing code will be running on the same one thread.

JList setListData threading issues

I'm loading contents of a file to JList component. If I do the loading in main thread, everything seems to be OK - contents are loaded. But when I move loading code to separate thread, select an item in a list and try to reload the list, I get random NullPointer or IndexOutOfBounds exceptions. I'm sure this is some kind of Swing threading issue, but can't determine what.
This is my thread code:
#Override
public void run() {
List<String> textLines = null;
textLines = splitter.split(model.getLedMaxChars(), textLoader.loadText(file));
listener.onTextLoaded(textLines);//listener is in main Swing code
}
Controller is responsible for listening:
#Override
public void onTextLoaded(List<String> textLines) {
view.fileLoaded(model.getCurrentFile());
view.setTextLines(textLines);
view.enableListComponent();
}
And the view updates:
public void setTextLines(List<String> textLines) {
jList.setListData(textLines.toArray());
}
I've tried to leave thread to hang by adding while(true); loop - then everything works OK. If I hit reload without selecting item in a list, everything works too.
Could anyone explain what I'm missing here?
Swing components are usually not thread-safe. This means that only the Swing worker thread should do any modifications:
Runnable worker = new Runnable() {
public void run() {
jList.setListData(textLines.toArray());
}
};
SwingUtilities.invokeLater(worker);
See also:
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html
Swing is not thread safe, so when you are manipulating GUI elements from other threads many weird things may occur. In your case the simplest solution (but probably not the best) would be to use SwingUtilities.invokeLater

Categories