Applet flickers with no image present - java

Im currently building an applet and ran into an updating/repainting problem. I have string drawn that updates the coordinates of the mouse. The problem starts when I move the mouse. The coordinates update (by means of repaint() within the mouseMoved() method, but the applet flickers until I stop moving.
I've tried looking for solutions, but they only deal with if there was an image present. My applet only contains buttons, text (drawString()) and a gradient background. When it flickers, everything but the buttons flickers. Is there an alternative to stop the flickering when dealing with an applet that DOESNT use image files?

In Java Swing there is a concept of Event Dispatch Thread (EDT):
You can try putting in your Applet.init() method
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
and to perform all related GUI stuff only in EDT.

Related

Showing GlassPane before entering loop

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

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

JButton Sub-Class Not Displaying Button until Clicked/Transparency Error

I have run into yet another issue with my program. I have made several JButton sub-classes to do specifically what I need them to do. The problem is that the buttons don't show up until I either click where they are supposed to be or if I hover the mouse over them (when I had setRolloverEnabled() to true). I originally had them all set for setRolloverEnabled() to true. But I understood that when I did hover the mouse over top of them, it had an ugly blue outline of the button which I didn't like at all. So is there any way to make them visible without having to hover over them, or without having to click them?
I have a background on my JFrame (I sub-classed JPanel and overrode the paintComponent() method) allowing JFrame to maintain its role as a container). Also in Adobe Photoshop I have designed the buttons and on the outer edge it has some transparency, I saved the files as .png so the transparency would be kept, but when the buttons are placed in the frame, there is an ugly blue outline still where it should be transparent. Any help on that.
Any suggestions would be appreciated. Below is the code for one of my Button classes.
public class Button extends javax.swing.JButton {
//This Button class is not the AWT Button object.
//It is a custom class designed by me.
public Button(ImageIcon normal){
setRolloverEnabled(false);
setVisible(true);
setIcon(normal);
setSize(normal.getIconWidth(),normal.getIconHeight());
}
public Button(ImageIcon normal, ImageIcon rollover){
this(normal);
setRolloverIcon(rollover);
}
public Button(ImageIcon normal, ImageIcon rollover,ImageIcon selected){
this(normal,rollover);
setSelectedIcon(selected);
}
}
There is a good chance you are not creating your GUI in the Event Dispatch Thread. Swing painting is single threaded by design. If you try to draw your components (even if you dont do it on purpose), the results will be varied. There are well documented methods to properly instruct the jvm to paint your components, including SwingWorker and SwingUtilities.invokeLater(Runnable). Take a look at this tutorial to get more info.

Displaying JWindow in the event dispatching thread

What I am trying to do is have a small splash screen appear while my program is loading something. This is what I have:
SplashScreen.showSplashScreen();
// Do stuff that takes time.
SplashScreen.hideSplashScreen();
All the showSplashScreen() method does is create a new JWindow in the middle of the screen and make it visible.
Now this code is called from the event dispatching thread, so when the showSplashScreen() method is called, I don't get to see the JWindow until the thread has finished, which by then, I don't need the window anymore. What would be the best way to go about showing this splash screen while I was waiting?
Not sure if this is the "best way", but a mechanism I've used before is to do your initialisation on a thread other than the EDT, but show your splash screen using SwingUtilities.invokeAndWait. That way, you'll at least get to see the splash screen even if your initialisation is quick (if that's what you want to happen).
So on your init thread, you go:
SwingUtilities.invokeAndWait( /* Runnable to show splash screen */ );
// Do stuff that takes time.
SwingUtilities.invokeLater( /* Hide splash screen, display main GUI */ );
There is a java.awt.SplashScreen class that was introduced in 1.6, tried using that?

Working with frames and Java AWT

I am currently making a program with the AWT GUI and I'm running into a problem. I basically want an image in the top left hand corner of the screen, and a column of buttons on the right of the image. This isn't what's happening though. When I run the applet, I click a popup saying "Start Program" and then the picture I want is in the applet window itself and the column of buttons is in another window by itself. This is what it looks like:
Is there anyway to fix this so that the image and the buttons are in the same window?
Yeah. You're creating a frame but your graphic isn't inside the frame. Can't tell much without the code, but the AWT Tutorial at java.sun.com isn't bad on this stuff.
Okay, a little more (I haven't used AWT in a long time.)
Here's the couple of issues you have. A Frame is a kind of Window -- it wants to be a separate window with its own close button and so forth.
When you create your graphic, you have to tell it was component its parent is; you're somehow parenting it to the Applet. So you have some piece of code that looks like
add(myComponent);
in the context of the Applet as this.
public class myApplet extends Applet {
// lots of stuff here creating your canvas, putting the image in it
// and so forth. There's an example, see fn 1.
// When you're done, you have a component, call it myImage.
add(myImage);
}
You have a Frame, and you're adding your buttons to that.
public class MyFrame extends Frame {
add(new Button(...));
add(new Button(...));
}
You need to move the code that adds your Canvas into the Frame class in some method.
(WARNING: this is not complete Java code, I don't recall the names of the right methods offhand. Probably the init() method in the Applet, at least.
fn1. http://java.sun.com/developer/onlineTraining/awt/contents.html#simpleexample

Categories