Repaint and Mouselistener Java - 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.

Related

Repainting JPanel multiple times from an EDT

I have a JPanel with some JButtons on it. When the JButtons are clicked, an event handler is invoked. Within this event handler, I would like the capability of having the JPanel repaint multiple times. There is a lot of processing that occurs in this event handler over the course of several seconds, and I need to be able to update the JPanel to display incremental updates to the user. However, when I call repaint() on the JPanel within the event handler, nothing seems to happen. The JPanel waits to repaint until the event handler has returned.
I have tried using the repaint(long tm) method, but that doesn't seem to help. How do I get this desired behavior of repainting a JPanel multiple times from within an EDT?
Swing is single threaded, so event handlers and painting occur on a single thread (the EDT). If you have computation that takes time and attempt to do so on the EDT, no repainting (or anything else) can be performed. To overcome this, perform the long running tasks on a separate Thread or use a SwingWorker
As most all similar question answers will tell you -- use a SwingWorker to do the long-running task. Push updates to the GUI via the SwingWorker's publish/process method, and when the updates are passed into the GUI, repaint it. This way you avoid stomping on the Swing event thread and avoid freezing your program. Please check out Concurrency in Swing. Also have a look at my code in this answer to a similar question.

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...

Java graphics events not occurring in the order I expect them to

So I'm making a graphical card game. Each card is a JPanel with a button and two images associated with it. I have a flip method, which is the first thing I call in my action listener when a card is clicked on.
public void flip()
{
if(b1.getIcon() == card2) b1.setIcon(card1);
else b1.setIcon(card2);
revalidate();
repaint();
}
However, for some reason the card doesnt flip (meaning the icons don't change) until some point after I call this method. For example, when I put a Thread.sleep after I call flip, I would assume that my program would pause after flip is completed, but it doesnt! It sleeps with the images not yet switched, and only switches them some at point after the sleep time has ended.
This is causing some major problems when I have a human play an AI in this card game, because AI events are happening before cards flip on the screen, even though I am calling flip() before I do any AI code. Can anyone clue me in as to what is going on here?
Repaint is a request to Swing to redraw not a call to redraw. Under the covers repaint() is posting a repaint job onto a queue of events. Along with that repaint job things like mouse moves, mouse clicks, keyboard activites, etc are posted there too. The Swing thread comes by and periodically executes jobs from that queue to redraw the UI, deliver mouse and keyboard events to components, etc. In fact the swing thread delivers these events quite frequently, but it just depends on how much work your UI is doing on that Swing thread. When it's out delivering mouse clicks, keyboard events, and redraws it can't read from that queue. So if your code takes a long time to repsond to any event the ability for swing to respond timely to new events is reduced or all together blocked.
That's why if you execute a blocking service call over the network with the Swing event dispatch thread your UI stops drawing until that call returns. This is why its important to move long running jobs like network calls off the Swing Thread, and use SwingUtilities.invokeLater() when the call comes back so you can update the UI on the Event thread. (invokeLater() does this by posting a job onto the Swing event queue we talked about above).
This is also why it's a terrible idea to call sleep on the Swing event thread. If you put that thread to sleep it can't service events from the queue. And the repaint() you requested isn't going to be done while the Swing thread is sleeping.
First remove your sleep call. Second. Don't write code that depends on painting to finish before executing more logic. Repaint and revalidate are special calls, and Swing will combine requests to repaint/revalidate so it doesn't redraw 10 times in a row (wasting vital cpu time).
Swing can't redraw your panel until you let the thread that called you leave the method it first called you back on. The sooner the thread leaves that method the sooner your repaint() will happen.
You haven't explained why you want the repaint to happen immediately so I can't give you any advice on how to structure your code so you don't care about it. But I'm telling you, you shouldn't care that the repaint hasn't happened yet.
Totally agree with #chubbsondubs. I just wanted to add that if your goal is to have some event happen some time after flip is called, consider using a swing timers. As you are painfully aware, calling Sleep does not have the desired effect. But if instead, you
create a timer for say 1 second
create an action to be performed when the timer fires
start the timer
then you can create the delay that you want without blocking the event dispatch thread.
public void flip()
{
if(b1.getIcon() == card2) b1.setIcon(card1);
else b1.setIcon(card2);
revalidate();
repaint();
javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something interesting
}
});
t.repeats(false);
t.start();
}

java event queue event dispatch flush/trap events

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.

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