In my SWT Application i wish to use a progress bar (org.eclipse.swt.widgets.ProgressBar)
i found examples but could not understand the proper flow and usage i need to perform background task for which, i was paused at the algorithm phase like i can analyze that there should be two threads one for background job, another for a progressbar both should execute simultaneously, i could not figure out the Implementation of this,i found plenty of examples but,i was puzzled where should i place my background task code (still searching). Can anyone provide sample example that suits me.
Did you see update a progress bar (from another thread) from SWT ProgressBar snippets page? It explains a lot.
ProgressBar have to be asynchronous to work correctly in every GUI framework. It's job is to show some value independently on main (GUI) thread. So you have to write your own thread, which will maintain the ProgressBar, resolving current value of it and show the changes of value (rendering progress by widget itself).
In Swing, you don't have to create you own thread for ProgressBar, because the class already implements upper proposed behavior (makes itself another thread and manage the work for you). But because SWT is platform dependent (and for other reasons), you have to manage this by yourself.
Related
I have recently learnt that jMonkey operates on only a single thread which is its openGL render thread. However I'm not able to understand it completely. I can understand that it executes all update and initialize() calls on a single update loop but input should be independent of this update loop, otherwise it will become a polling mechanism.
What exactly happens when the jMonkey application starts. Three tasks that it needs to do is run a update loop, run initialize methods of app states once, do rendering and constantly cater to events? How does it manage all of this via a single thread?
What happens when I add a new app state in the initialize method of another app state?
In input handling input manager notifies the various listeners about events. How are nifty callback events say onClick() are handled on the same render loop?
Lastly in which order this listen- update-render loop runs and where we can find code related to it?
jME uses an approach that's very common in a lot of game engines (and also used in some other user interface libraries such as Swing).
Everything that the game engine does is done in one thread. This can be called the LWJGL thread but as jME can work with alternatives to LWJGL it's more generic to call it the Render Thread or just the jME Thread.
Everything is indeed done on the Render thread, and it does indeed use a polling mechanism. For example if you are holding down the "left" key then each frame the relevant control or app state will be called on the render thread and will move you left by an amount modified by tpf. Tpf is time-per-frame and is very important for keeping smooth movement and letting game systems run at the same speed independently of frame rate.
The only thing within jME3 that commonly uses a separate thread is the Physics Engine. That has a thread that it uses for doing the physics updates and then changes are pushed through to the Render thread using appropriate mechanisms. The system handles this for you though so it is not something you need to worry about.
The thread runs around a game loop. Each time around the loop it checks for things it needs to do (like enqueued tasks, initialize app states, render, etc. It calls update in each active Controller and control, etc). Once it has finished updating everything it then goes on to perform the render. All of this happens every single frame, but computers are so fast that it can still handle all of that and render the game at good frame rates.
That's an implementation detail that you shouldn't need to worry about except to know that it will definitely work. The adding actually gets queued up and handled in the next frame I think.
Everything is handled from the same loop. jME calls through to Nifty to allow Nifty to do its processing. As part of that processing Nifty detects the events and fires off the callback. This means that the callbacks are already coming in on the render thread so you can safely modify the scene graph. jME uses some specially written collections such as SafeArrayList to allow you to modify the scene graph at the same time as iterating over it.
Update, Render, Update, Render, etc. Events firing generally happens as part of the update process when an update is detected. To find the code start by looking in the Application class, you should be able to find the main game loop in there by tracing through from the start() call.
The jME3 Threading Tutorial covers a fair amount of this:
http://hub.jmonkeyengine.org/wiki/doku.php/jme3:advanced:multithreading
I have a GUI(JFrame), with two Buttons and 1 Panel to show the result. One Button is to start the algorithm, one for stopping it. By pressing start, a method is called and it starts running. The runtime of this method varies from couple of seconds to 2-3 minutes, depending on the input.
The problem I have hereby is, by pressing the start-button, the GUI gets completely locked. I cannot press any button till the algorithm terminates. It would be great to be able to stop the algorithm and to visualize parts of the solution after a certain amound of time.
I checked every single line of the Frame, there is nothing that disables it.
//If needed I can provide code, but its pretty long and just some hints and reasons for the problem would be great and I try to fix it by myself.
thanks in advance.
Don't put long-running tasks on the EDT, or the Event Dispatching Thread. Use threading or a SwingWorker instead. Hopefully that's enough google keywords to get you started. :)
It sounds like your algorithm is running in the same thread as the UI components. You probably want to read up on Concurrency and Concurrency in Swing to better understand how to create threads, monitor execution, integrating these concepts with a Swing-based user interface, and so forth. At a very high level, you are going to need to somehow spawn a new thread when your algorithm starts and observe it for intermediate state changes to update the UI. You only want user interface related code running in the event dispatch thread.
Good day, I want to make in java swing opening tabs in new threads and it would have had the opportunity to run time-consuming tasks to switch between tabs. Tried it, a copy of the tab implement the interface Runnable, but a new thread is not valid (in the debugger it starts hanging about 1 sec, and is killed), as I understand the constructor work out, and all the contents of the swing is placed in its major flows. I read about SwingWorker, but do not quite understand how you can apply it to my problem. If you can, please show an example. Thanks in advance.
P.S. This is network application, and "load" will serve as a work with the server. That is, in other words, to give the user the ability to switch between tabs until the current tab is a connection.
You should try to separate the code that does the actual work from code that specifies the GUI. You should search e.g. for the Model-View-Controller-Pattern (MVC).
This way the GUI code can run inside the event-dispatcher-thread (EDT) of Swing / AWT how it is more or less inteded. The code that does the actual work should be as independent from the GUI as possible. Now you can choose to run it in a dedicated thread or whatever fits best into you overall application architecture.
The last part is wire these two (the GUI and the domain logic) together, so that the GUI triggers the worker code or the worker code triggers GUI updates, or whatever satisfies the workflow requirements.
I'm developing a big project on Java Swing. It has a database connection, external devices managing and sd-cards processing.
I currently have a lot of heavy processes that run on the EDT thread, and making separated threads for all of them is a long long task that I'm trying to escape... Besides, It would probably introduce a lot of concurrency problems that I am not willing to handle.
The thing is that I want to introduce a loading JLabel with a loading gif while the long busy tasks are being processed. It is also important to highlight that I want my whole swing interface to be blocked while the long tasks are being done, just like it happens now, EXCEPT for the loading label.
Is there a way to actualize that label from another thread?
If you care about creating a good user experience, there really is no escaping using SwingWorker or similar, to offload work form the event dispatcher thread (EDT). If you need to really need to "block" the UI, you should use a JDialog with a progress bar or similar.
The short answer to your question is no. The Jlabel must be instantiated and added from the EDT.
However, you should be able to add the JLabel, you just have to make sure you do it before the long-running blocking tasks starts. Then remove it after it is done.
Anyway, this is a hack, and a lazy workaround for doing the right thing, and is not recommended. You might experience that you spend more time working around the issue and pulling your hair, than just do it properly with SwingWorkers.
I have a little java app to effectively "tail" an arbitrary collection of files defined in an ini file. My "LogReader" class extends JFrame, and does the heavy lifting; reading the collection of file paths into a vector, and then iterating over the vector, reading each file and adding the last X lines of each to a text areas on the tabs of a JTabbedPane. The process of building the vector and iterating over the files is kicked off by clicking a JButton, via an ActionListener.
The reading of the files worked fine (and still does), but the process of reading 20-some files, some growing as large as 30MB, takes some time. To help pass that time, I decided to add a progress screen, which says "Now reading file #3 of 26: c:\logs\superduper1.log", and so on. So I created another class, "SplashScreen", also extending JFrame, and added a JLabel that would indicate the progress. The SplashScreen class has an update() method, which just does a setText() on the JLabel.
The ActionListener on the JButton calls RefreshLogs(), which looks something like:
vctFileStrings.clear();
tpMain.removeAll();
frmSplash.update("Loading Configuration"); //Update the label on the Splash Screen instance
BuildVectorOfLogs(strConfFile); //Read the collection of files into the vector
frmSplash.update("Reading Logs");
ReadLogs(); //read the files, updating the Splash Screen as we go
and then ReadLogs() iterates over the vector, reading the files and building the TabbedPane.
What I noticed, though, is that when RefreshLogs() is called from within the ActionListener, the Splash Screen doesn't update. However, if I add RefreshLogs() to the constructor of the first frame, the splash screen works as expected (updates progress on each file). After some experimenting and reading, I think that I need to create a worker thread that reads the files, while updating the splash screen in the event-dispatch queue.
My questions are:
- Is my thought correct? Is there some simple alternative to implementing threading that would allow me to update the splash screen from the method called by the ActionListener?
- If this would be best accomplished using threading, what scope of the activity would I need to thread? Would I need to put all of the file I/O activities into their own thread? Should I put the GUI activities (label updates) in their own thread, so they occur separately from the JButton click event?
I would say: yes, your thoughts on offloading the reading of large files to a separate thread are correct. You should never perform long tasks on the Event Dispatch Thread, since while that thread is busy, the GUI will be unresponsive, and you application will feel slow.
This sounds like good case for SwingWorker. This class allows you to perform slow requests (such as disk or network access) on a separate thread, with progress updates being fed back to the GUI with the EDT. SwingWorker looks after all complexities of switching between threads. All you have to do is implement your business logic in the appropriate places.
Sun has a tutorial on SwingWorker.
Yes, you should put your time intense reading into a separate thread. Now you do everything in the event-dispatching thread (EDT), which would update your GUI but is busy reading your data.
You can use SwingWorker for this. Have a look at Using a Swing Worker Thread which looks like what you need.
One suggestion for you, to figure out how to do this, and in case you are using NetBeans or have access to NetBeans, is to look at the default Java Desktop Application template. It creates a pre-wired desktop app with progress bar built into a status bar, that will automatically get updated when any "Action" code gets executed. It leverages the Action API which is also pre-wired to run in a background thread.
By looking at that auto-generated code you'll be able to properly and easily implement it in your own.