swing - Create a plain message box that disappears after a few seconds in Java -
i wonder best approach make joptionpane style plain message box disappear after being displayed set amount of seconds.
i thinking fire separate thread (which uses timer) main gui thread this, main gui can carry on processing other events etc. how make message box in separate thread disappear , terminate thread properly. thanks.
edit: come following solutions posted below
package util; import java.awt.borderlayout; import java.awt.dimension; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.swingconstants; import javax.swing.timer; public class disappearingmessage implements actionlistener { private final int one_second = 1000; private timer timer; private jframe frame; private jlabel msglabel; public disappearingmessage (string str, int seconds) { frame = new jframe ("test message"); msglabel = new jlabel (str, swingconstants.center); msglabel.setpreferredsize(new dimension(600, 400)); timer = new timer (this.one_second * seconds, this); // need fire once make message box disappear timer.setrepeats(false); } /** * start timer */ public void start () { // make message box appear , start timer frame.getcontentpane().add(msglabel, borderlayout.center); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); timer.start(); } /** * handling event fired timer */ public void actionperformed (actionevent event) { // stop timer , kill message box timer.stop(); frame.dispose(); } public static void main (string[] args) { disappearingmessage dm = new disappearingmessage("test", 5); dm.start(); } }
now question that, cam going create multiple instances of class throughout course of interaction between user , main gui, wonder whether dispose() method cleans every time. otherwise, may end accumulating lots of redundant objects in memory. thanks.
i think in situation, can't use of joptionpane
static methods (showx...
). have create joptionpane
instance instead, create jdialog
, show jdialog
yourself. once have jdialog
, can force visibility.
// replace joptionpane.showxxxx(args) new joptionpane(args) joptionpane pane = new joptionpane(...); final jdialog dialog = pane.createdialog("title"); timer timer = new timer(delay, new actionlistener() { public void actionperformed(actionevent e) { dialog.setvisible(false); // or maybe you'll need dialog.dispose() instead? } }); timer.setrepeats(false); timer.start(); dialog.setvisible(true);
i haven't tried can't guarantee works think should ;-)
of course, here timer
javax.swing.timer
, else mentioned, you're sure action run in edt , won't have problem creating or terminating own thread
.
Comments
Post a Comment