java event queue event dispatch flush/trap events - java

I have a design related question that I am trying to find an answer to.
Here is the scenario.
Suppose that you want to do something expensive (time-consuming) as a result of user input (e.g. loading huge amounts data from some database, reading large files). The strongly recommended way is to do the time-consuming work in a separate thread and never ever block the EDT, or else the GUI will become unresponsive.
There are scenarios however when you should not provide inputs to the GUI unless the background task is finished. In my specific case, only after the background work is finished, I can determine which GUI elements should be visible and enabled/disabled. Only those GUI elements which should be visible and enabled should respond to the user inputs otherwise the behavior may be unpredictable in my specific case.
This is what I am doing to handle such a scenario.
Step 1: Before I am about to start a time-consuming operation.
Change the cursor to a busy cursor.
Add mouse listeners to the glasspane of component's top-level frame.
Make the glasspane visible so that it can receive mouse events. The glasspane doesn't do anything as a result of mouse inputs.
Step 2: Execute the time-consuming operation in a background thread. The background thread has a finally block that notifies the event thread when the job is finished (completed or aborted due to an error).
Step 3:
Switch the mouse cursor back to normal.
Remove listeners from the glass pane.
Make the glasspane invisible, so that mouse events go to their intended recipients.
Is this the correct approach to handle such situations?
What do you guys recommend?

SwingWorker can be used in this context. Related controls can be disabled when the background task is started and re-enabled in done(). In this related example, the run button is conditioned to toggle between "Run" and "Cancel".
Addendum: A back-port to Java 1.5 is available here.

Related

Repaint and Mouselistener Java

So I have this paradox where I have a mouseListener added to my mainframe. When mouse entered this has a loop to check if the time that passed is exceeding a certain limit so it is registered a hold. It has to be in a thread because otherwise, I could not check for clicks as my main Thread would be blocked (or would it?). But the problem is that I want to show info while the mouse Button is still clicked requiring me to call repaint from within the thread, which won't work as repaint only works from the main Thread, yet this one has to be free for the MouseListener...
Does anyone have an idea how to solve this Problem?
When mouse entered this has a loop to check if the time that passed is exeeding a certain limit
Don't use a loop. If this is executed in the listener then you will be blocking the Event Dispatch Thread (EDT).
Instead use a Swing Timer. When you enter the component you start the Timer. The Timer will then generate an event after your specified time interval.
However, you can also stop the Timer if some other event is generated and you want to reset the timer.
This will not block the Event Dispatch Thread (EDT) and events will still be generated normally.
i want to show info while the mouse Button is still clicked
Not sure what "still clicked" means. If the button is still pressed and you are executing code from an ActionListener you will block the EDT and the GUI won't be able to repaint itself until the long running task is completed.
Read the section from the Swing tutorial on Concurrency for more information about the EDT.

Animation in Swing

I have a project written using Swing, and I want to make it more smoothly (like JavaFX is) by adding animation to some components(JButton, JScrollPane, JSplitPane) using javax.swing.Timer.
That is not a game. I want to use the Timer for short animations like mouseHover events, dropdown, or scroll. But the problem is, a lot of Timer objects should be created.
Question: What action does it perform for JVM? I would start and stop a lot of Timers during app session.
What action does it perform for JVM? I would start and stop a lot of
Timers during app session.
Swing Timer fires ActionEvents at specified intervals to animate object providing function: start(), stop(), restart(), and most importantly setDelay(int delay) to fire successive action events in specific inerval ensuring all such event task are executed in the EDT(event dispatch thread). Waiting state of All created Timers are managed by a single shared thread, TimerQueue, created by the first Timer object that executes.
Handling timer might be tedious. Instead of writing same Timer handling code every time, I would go for using a library instead like swing TimingFrameWork.
That is not a game. I want to use the Timer for short animations like
mouseHover events, dropdown, or scroll. But the problem is, a lot of
Timer objects should be created.
this is job only for one Swing Timer together with (mouseHover events, dropdown, or scroll) focus from mouse or key_events, Swing Timer has implemented start(), stop() and restart(), last one is important for waiting until users action ended
logically isn't possible to generating more than one event, different situation will be in the case that there is multitouch display, and in this case is only one event important too, rest of events are directions, scalling, factor, etc...

SWT Based GUI getting black on maximizing from minimizing staus in Full Size

I've a GUI based on Eclipse SWT/RCP . When that GUI is in Full Size and I minimize it and then maximize it , I see a dark/black over the Ui for a second or more and then it becomes normal. I want to know, what might be the reason for same
Following is the screenshot -
This usually indicates that you have a code that runs longer than it should on an event listener and the paint events are not dispatched until that code is done. Hence you see the black areas until they are dispatched and painted. I recommend checking the logic on listeners especially for resize and focus events if you have any.

Pattern for blocking Java Swing user in worker thread

As most Java programmers know, updates to Swing GUIs should only be done on the AWT event dispatching thread and the recommendation is that long-running processes be executed on a "worker" thread, with updates sent to the event dispatching thread using SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater().
How do you stop the user from proceeding with the application while the long-running process is completed? Do you gray out the controls and then have the worker thread reenable them using the SwingUtilities calls mentioned above?
Is there a better alternative pattern?
I would consider 3 solutions :
disable the components of the panel : it's generally what I do. Unfortunately, Swing does not provide a simple way to disable a panel and all its children, but it is easy to do the recursion (see this other SO answer for that). Another problem is that some Swing components look the same when enabled and disabled (JList, for example)
hide the panel with a CardLayout : in a panel with a CardLayout, add 2 components. The first is the panel that hosts the components to inactivate, and the second is a panel showing a "loading" or "please wait" message. A simple JLabel in a Gridbaglayout does the trick. Then, you just have to switch from one to another. I use this technique for places where a result of a computation/request is to be displayed.
put some kind of component on top of the panel that consumes the mouse events : you can do it yourself with a LayeredPane, or you can use a dedicated utility. JXLayer can do that (I read that JXLayer will be included in Java 7, so this may become the 'standard' solution to this kind of problem).
There are several ways and the selection of which, mostly depends on the design and layout of your GUI.
Use a Progress Bar - Replace the panel or an area that you don't want a user touching with a progress bar. This will prevent you from having to deal with events you don't want yet, while still making it clear to the user that something is happening in the background.
Disable buttons and add a Wait Cursor - Use setEnable(false) while work is being done and nd possibly change the cursor to a Wait Cursor. This again makes it clear that an option is not available yet only for a temporary period.
Don't respond to events or throw up a GlassPane - This is less user-friend as it makes the application look unresponsive, however it can acceptable in some situations.
One way I have seen it done is to use Jframe.setGlassPane() and set a component that eats all events. You can also be creative and use flash kind of rotating-wait gif in your glasspane. But note that setting a glass pane may not be all you want. For more advanced requirements, you may have to play around with event-queues.

Java swing progress bar from EDT problem

This is for the swing experts out there. I have spent considerable time on this problem, so it is going to take me a few lines to explain the problem.
I have a standalone java swing application (java 6). In my application, I have a frame with a radio button group. I have a single action linked to all the buttons in the group. The action checks to see which radio button is selected and performs some work. The "work" involves some background computation as well as some painting in two other frames in my application. The background computation is multi-threaded.
I would like to display a progress bar when the user selects one of the radio buttons.
However, when a radio button is selected, while the action to the radio button is happening, the progress bar never appears. I have tried jdialog type progress bars, glass panes, etc. None of them appear until the "work" is all completed. This seems to be because Swing does not finish painting the radio button until the "work" in the corresponding action is completed. And since the EDT only does one thing at a time, the progress bar dialog (or glass pane) is never displayed.
I then tried to use a SwingWorker to do all this "work". Start the progress bar (or activate a glass pane), start the SwingWorker and close the progress bar (or deactivate the glass pane) in the done() method for the SwingWorker. This seems to bring up the progress bar fine, but the painting which is part of the "work" is sometimes not completed, leaving me with some painting artifacts (the paintComponent method is pretty complicated, so do not want to reproduce here). The artifacts disappear if I resize the window. In fact, this happens if I use a class which extends Thread instead of SwingWorker too. This is all because Swing is not threadsafe and I am trying to do GUI work from a thread other than the EDT. I understand that part.
What do I do? "work" takes about 30 seconds and that seems too long to go without showing the user some kind of indication that the program is working. I have also tried changing the cursor to a wait cursor and have run into the same problems as above. The only thing that I can do is disable the frame and set the title of the frame to some text like "working..."
Anybody seen this problem before?
I think you are right to do the work in the SwingWorker thread, but you shouldn't be trying to do your painting there.
I'd be inclined to:
Have the ActionListener show() the progress bar, set off the swingworker then exit
Have the worker thread do the work, and periodically call repaint() on the progress bar component (this is guaranteed to be thread safe)
Progress bar has it's own paintComponent (which will be automatically called on the EDT). If necessary, this can read some variable that is updated by the worker thread to measure progress
When the worker thread finishes, have it call invokeLater() to run a final close down function on the EDT, which will hide the progress bar and do any other GUI-related cleanup / show a completion message to the user etc.
When you moved the work from the EDT to the swing worker (which was the right thing to do), it sounds like both the work and the painting moved to the swing worker. The painting should still happen on the EDT. You can achieve this by using SwingUtilities.invokeLater to invoke a repaint from the background thread, or by using the SwingWorker.publish(V...), which will take notifications from your worker thread and make them available on the EDT via the SwingWorker.process(V...) template method (which you override). Your process override can handle the intermediate notifications by repainting a portion of the screen, updating progress, or taking some other appropriate action as desired. Any UI changes done here will be visible without waiting for the rest of the work to complete.

Categories

Resources