Showing GlassPane before entering loop - java

(In my applicaton with Swing GUI) I want to display GlassPane during some work performed in a loop or method, which is called after clicking JButton.
For example:
(action performed after clicking a button)
if (item.equals(button)) {
glassPane.setVisible(true);
someTimeConsumingMethod();
glassPane.setVisible(false);
}
Running this code results in not showing the glassPane during execution of someTimeConsumingMethod() - GUI just freezes for a moment, before result is displayed. Removing last line in that loop (glassPane.setVisible(false);) results in showing glassPane after the method is done (when GUI unfreezes).
Is there a simple way to show that glassPane before GUI freezes, or I need to use some advanced knowledge here? (threads?)
UPDATE1:
I've updated my code according to davidXYZ answer (with two changes):
(action performed after clicking a button)
if (item.equals(button)) {
glassPane.setVisible(true);
new Thread(new Runnable(){
public void run(){
someTimeConsumingMethod(); // 1st change: running the someTimeConsumingMethod in new Thread
// instead of setting glassPane to visible
}
}).start();
// 2nd change: moved glassPane.setVisible(false); inside the someTimeConsumingMethod(); (placed at the end of it).
}
The point of 1st change is that setting glassPane visible in new thread right before running someTimeConsumingMethod in my GUI thread was revealing the glassPane after someTimeConsumingMethod finished (double-checked this).
Now it works fine, thank you for all answers. I will definitely check all the links you provided to actually understand threads!
UPDATE2:
Some more info: someTimeConsumingMethod(); in my application is prepering new Swing Components accoriding to the XML data (cards builded from JButtons and JLabels with few JPanels where needed, and adding them in correct places).
UPDATE3:
I am trying to make it work using SwingWorker's invokeLater method. Now it looks like that:
(action performed after clicking a button)
if (item.equals(button)) {
glassPane.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
someTimeConsumingMethod();
glassPane.setVisible(false);
}
});
}
It works not that good as code from UPDATE1 (but still - it works). Problems are:
glassPane loads without .gif animation (file is setted up in custom glassPane class - it works with UPDATE1 code)
there is small delay at the end of "working" process - first cursor changes to normal (from the WAIT_CURSOR), and after very short moment glassPane disappear.
Cursor is changed by the custom glassPane class on activation/deactivation (no delay using new Thread way).
Is it correct way of using SwingWorker's invokeLater method?
EDIT: My mistake, I confused SwingWorker with SwingUtilities.invokeLater(). I guess the image issue is due to GUI freezing when the someTimeCOnsumingMethod starts.

GUI just freezes for a moment, before result is displayed. Removing last line in that loop (glassPane.setVisible(false);) results in showing glassPane after the method is done (when GUI unfreezes).
this is common issue about Event Dispath Thread, when all events in EDT are flushed to the Swing GUI in one moment, then everything in the method if (item.equals(button)) { could be done on one moment,
but your description talking you have got issue with Concurency in Swing, some of code blocking EDT, this is small delay, for example Thread.sleep(int) can caused this issue, don't do that, or redirect code block to the Backgroung taks
Is there a simple way to show that glassPane before GUI freezes, or I need to use some advanced knowledge here? (threads?)
this question is booking example why SwingWorker is there, or easier way is Runnable#Thread
methods implemented in SwingWorker quite guarante that output will be done on EDT
any output from Runnable#Thread to the Swing GUI should be wrapped in invokeLater()
easiest steps from Jbuttons Action could be
show GlassPane
start background task from SwingWorker (be sure that listening by PropertyChangeListener) or invoke Runnable#Thread
in this moment ActionListener executions is done rest of code is redirected to the Backgroung taks
if task ended, then to hide GlassPane
create simple void by wrapping setVisible into invokeLater() for Runnable#Thread
in the case that you use SwingWorker then you can to hide the GlassPane on proper event from PropertyChangeListener or you can to use any (separate) void for hidding the GlassPane
best code for GlassPane by #camickr, or my question about based on this code

You are blocking the EDT (Event Dispatching Thread, the single thread where all UI events are handled) with your time consuming job.
2 solutions:
Wrap the calls to:someTimeConsumingMethod();glassPane.setVisible(false); in SwingUtilities.invokeLater(), this will allow the frame to repaint itself once more. However this will still freeze your GUI.
Move your someTimeConsumingMethod() into a SwingWorker (this is the recommended option). This will prevent your GUI from ever freezing.
Read the javadoc of SwingWorker to understand better what is going on and how to use it.
You may also learn a lot in this tutorial about Swing and multi-threading

JButton startB = new JButton("Start the big operation!");
startB.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent A) {
// manually control the 1.2/1.3 bug work-around
glass.setNeedToRedispatch(false);
glass.setVisible(true);
startTimer();
}
});
glasspane here used here is FixedGlassPane glass;
ref: http://www.java2s.com/Code/Java/Swing-JFC/Showhowaglasspanecanbeusedtoblockmouseandkeyevents.htm

Guillaume is right. When you are on the main thread, each line will finish before the next line. You definitely need another thread.
An easy way to solve your problem is to spin off the display of the glasspane in another thread (normal thread or Swing threads - either will work fine).
if (item.equals(button)) {
new Thread(new Runnable(){
public void run(){
glassPane.setVisible(true);
}
}).start();
someTimeConsumingMethod();
glassPane.setVisible(false);
}
That way, a different thread is blocked by setvisible(true) while someTimeConsumingMethod() runs on the main thread. When it's done, glasspane will disappear. The anonymous thread reaches the end of the run method and stops.

Related

Refreshing a JFrame

I have done some digging around on this, however, I still can't seem to figure it out. Please excuse me, I haven't been programming for long.
Background: When I click on my run button it should create a second JFrame and update the background colours of JPanels on the second frame, periodically, once per iteration, throughout the run that the JButton starts.
Problem: The second frame is created, but stays blank until the loop, started by the JButton is finished, and it only displays the final state.
I have tried: invalidate(), validate(), repaint(), setVisible(true).
I have tried to run it in a separate thread.
I have even tried sleep(), in case it doesn't have enough time to update. Is there something else that I can try?
I think I would have overwritten the void paint(Graphics g) method which is called by the OS when redrawing is needed and add your drawing routine there. Don't forget the super.paint(g) call. You can then manually trigger redrawing (from inside your loop) by a call to void update (Graphics g); (calling void repaint() should work too)
The second frame is created, but stays blank until the loop, started by the JButton is finished, and it only displays the final state
If your ActionListener attached to the JButton (or the Action) is implemented like
public void actionPerformed( ActionEvent e ){
updateColor();
...
updateColor();
...
updateColor();
}
then the behavior you are seeing is exactly as expected.
Swing is a single threaded framework. When your ActionListener updates the background color, a repaint will be scheduled (emphasis on schedule, which is something different from performed). Since your loop in the ActionListener is still occupying the single thread (the EDT), the repaint cannot be executed.
As such, the first time the repaint can be executed is after you have released the EDT by finishing your loop. At that moment, the background color has already changed to its final color, and that is all what you will be seeing.
A possible solution to be able to see the background change is to use a javax.swing.Timer (and not the java.util version). A click on the JButton can start the timer, and each time the timer is triggered you change the background color to the next color. The moment the final color is reached, you stop the timer.

Why does the second JFrame does not show components?

I have the first JFrame and it works fine. When I push a button it is supposed to show a JProgressBar frame , but i get empty JFrame. I open it with
p = new Progress("1/3");
p.setMax(2);
p.setProgress(0, "Getting bytes...");
Anyone know why?
EDIT:
I am going to explain more detail(Because someone misunderstood and corrected my post in the wrong way) - On my main class i start the first JFrame:
new Crypt();
And in the Crypt class i have registered a button ActionListener. OnClick it opens a second JFrame But it is empty:
p = new Progress("1/3");
p.setMax(2);
p.setProgress(0, "Getting bytes...");
The Progress class
Screen shot
in the Crypt class i have registered a button ActionListener. OnClick it opens a second JFrame But it is empty
Code invoked from an Swing listener executes on the Event Dispatch Thread (EDT). The EDT is responsible for painting Swing components. Since your code is executing a long running task on the EDT y9ou are preventing Swing from painting the component until the task is finished.
You need to start a separate Thread for your long running task. Or better yet you should probably be using a SwingWorker. Read the section from the Swing tutorial on Concurrency in Swing which explains this in more detail and provides a working example of a SwingWorker.

Menu system works but cannot close

Okay, so I've got my menu system up and working from a JFrame. Everything seems to work really well, up until I click the button which starts a canvas. Now what the canvas does is intialize a JFrame which extends Canvas so I can't use a thread. Once the frame is up and running it calls a method which has a while true {} after this I am unable to close the frame. This has never been an issue before when running the canvas application using static void main. How can I fix this issue of the new JFrame not closing?
How can I fix this issue of the new JFrame not closing?
Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of creating an infinite loop, implement a SwingWorker for long running tasks. See Concurrency in Swing for more details.
1. Make this a rule of thumb when working with GUI application, that Always keep the UI work on the UI thread and Non-UI work on the Non-UI thread.
2. Second doNot mix up SWING AND AWT.
3. The main() method in Java Gui is not long lived, after scheduling the work in the Event Dispatcher Thread (EDT) the main() method quits. Now its solely the responsibility of the EDT to handle the GUI.
4. So never mixup the Non-UI process-intensive work, with the EDT.
Use EDT to handle the GUI.
Eg:
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
myframe.setVisible(true);
});
}

Get notified when the user finishes resizing a JFrame

I have a fractal generation component (a subclass of JPanel) inside a JFrame. When the user resizes the window, it takes quite a while to update the fractal to the new size.
I currently have a ComponentListener on the JPanel, but its componentResized event is called every time the user moves the mouse while dragging the window border. This means that the fractal is told to resize many times, and slowly (over the course of a few minutes) grows to the new size.
Is there a way to be notified when the user releases the mouse button, so that I can only change the fractal size when the user has finished resizing?
Others have reported this happening when the listener is attached to the JFrame instead, but this doesn't work for me (and others), for some reason.
Instead of starting the calculation each time you receive a receive-event, you can only start the calculation after you received the last event by using a timer, e.g. in pseudo-code (or at least code which I typed here directly and not in my IDE)
private Timer recalculateTimer = new Timer( 20, myRecalculateActionListener );
constructor(){
recalculateTimer.setRepeats( false );
}
#Override
public void componentResized(ComponentEvent e){
if ( recalculateTimer.isRunning() ){
recalculateTimer.restart();
} else {
recalculateTimer.start();
}
}
And you can still combine this with Andrews suggestion to use an image which you stretch until the calculation has actually finished.
you have look at HierarchyListener, where you can listening for HierarchyEvent with interface to HierarchyBoundsListener
basically nothing wrong with ComponentListener, but you have to wrapping expected events to the Swing Timer, in the case that events repeated, only to call Timer#restart(), output from Swing Timer should be Swing Action
It's a bit late, but it looks like no one found the correct answer. I found that when you call child.updateUI() inside a ComponentListener (componentResized block) of a window, this child resizes it self and updates its content. Using timers is unsafe.

Why setVisible doesn't work?

I have a swing GUI with border layout. in the NORTH I have added some component.
My label component which has GIF icon is invisible lblBusy.setVisible(false);
later a button make it visible like below. Why it does not show up?
btnDownload.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
lblBusy.setVisible(true);
btnCancel.setEnabled(true);
}
});
download = new Download(txtSource.getText(), new File(txtDestination.getText()), textAreaStatus);
download.start();
lblBusy.setVisible(false);
}
});
1) this is EventDispatchThread rellated issue, EDT quite guaranteed that all changes to the GUI would be done on one moment
2) you invoked ActionPerformed from JButton, and untill all events ended your GUI should be freeze or is unresponsible, same for JButton and JLabel in your case
3) better would be redirect reading for File contents to the Backgroung task e.g. SwingWorker or Runnable#Thread then JButton and JLabel will be changed and GUI would be during Background task responsible for Mouse or KeyBoard
or
4) dirty hack split to the two separated Action delayed by javax.swing.Timer, but in this case again untill all events ended your GUI will be freeze or is unresponsible
Most probably because the GUI was packed at a time the label was not visible, so no space was assigned to display it. For anything more definite, post an SSCCE.
It seems to me that you are writing lblBusy.setVisible(true); and after that lblBusy.setVisible(false); in the mouseClicked() method. Since you wanted to make it visible at the click of a button aren't you be using only lblBusy.setVisible(true);, instead of using both.
You can call lblBusy.setVisible(false); from the end of your Download Class though, once it's done doing what it does.
Regards

Categories