Java – make jlabel disappear
I am writing an application to perform a task and notify the user when the task is successfully completed Inform the user that I am using jlabel I want this jlabel to display messages and go back after a period of time I use NetBeans as my ide
This is the structure of my class
Summary, GUI code
abstract class Admin extends JFrame{ protected static jlabel lbl_message= new jlabel("some text"); // other functions and variables abstarct protected void performButtonClickAction(); }
Classes used to implement abstract functions and provide other functions
final class AdminActionPerformer extends Admin{ final public void performButtonClickAction(){ // code for doin the task if(task is successful){ new Thread(new Fader(Admin.lbl_message)).start(); } } public static void main(String[] args) { new AdminActionPerformer().setVisible(true); } }
Thread that causes jlabel to fall back
class Fader implements Runnable{ javax.swing.JLabel label; Color c; Fader(javax.swing.JLabel label){ this.label=label; c=label.getBackground(); } public void run() { int alpha=label.getGraphics().getColor().getAlpha()-5; while(alpha>0){ System.out.println(alpha); alpha-=25; label.getGraphics().setColor(new Color(c.getRed(),c.getGreen(),c.getBlue(),alpha)); label.repaint(); try { Thread.sleep(50); } catch (InterruptedException ex) { Logger.getLogger(Fader.class.getName()).log(Level.SEVERE,null,ex); } } } }
But the label did not disappear What did I do wrong here? Thank you:)
Attachment: I set jlabel opaque true Is that a problem? I want to initially display the label with the background color and then fade away
Solution
I agree with Johannes that updating the UI from different threads may not be good There are some mechanisms, such as swing worker and swing utilities Invoker, which can solve your wrong thread problem
But the bigger question I see is who you are arguing with your jlabel Jlabel is an ordinary component. Whenever its container is refreshed, it will be redrawn in its usual color This is the case of "who draws last, wins"
Alternative suggestion: why not simply fiddle with the color attribute of the label? If you bring the foreground color closer to the background color, you will see it fade When you change its color, the label will redraw itself, or you can use update() or repaint() to force redrawing, and I will forget it
edit
I think I see the real reason why this doesn't work You are setting the color of the graphic context of the label It doesn't work! Any component that smears its own part sets its color immediately before drawing anything, immersing its brush in ink Of course, the color it sets for drawing character glyphs is the original label color Your method works only if the label painting code stupidly forgets to set the color before drawing