Java:Show message dialog for 10sec and remove?
Hi i want to show JOptionPane.showMessageDialog(null, "A开发者_开发百科ppication already running");
for 10sec and then remove it.how can i dothat?
You can create a JOptionPane manually, without static methods:
JOptionPane pane = new JOptionPane("Your message", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(parent, "Title");
then you can show the dialog and fire up a timer to hide it after ten seconds.
I tried these answers and ran into the problem that showing the dialog is a blocking call, so a timer can't work. The following gets around this problem.
JOptionPane opt = new JOptionPane("Application already running", JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[]{}); // no buttons
final JDialog dlg = opt.createDialog("Error");
new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(10000);
dlg.dispose();
}
catch ( Throwable th )
{
tracea("setValidComboIndex(): error :\n"
+ cThrowable.getStackTrace(th));
}
}
}).start();
dlg.setVisible(true);
My Java is a bit rusty but you should be able to just use the standard Timer
class:
import java.util.Timer;
int timeout_ms = 10000;//10 * 1000
Timer timer = new Timer();
timer.schedule(new CloseDialogTask(), timeout_ms);
//implement your CloseDialogTask:
class CloseDialogTask extends TimerTask {
public void run() {
//close dialog code goes here
}
}
// =====================
// yes = 0, no = 1, cancel = 2
// timer = uninitializedValue, [x] = null
public static void DialogBox() {
JOptionPane MsgBox = new JOptionPane("Continue?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
JDialog dlg = MsgBox.createDialog("Select Yes or No");
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.addComponentListener(new ComponentAdapter() {
@Override
// =====================
public void componentShown(ComponentEvent e) {
// =====================
super.componentShown(e);
Timer t; t = new Timer(7000, new ActionListener() {
@Override
// =====================
public void actionPerformed(ActionEvent e) {
// =====================
dlg.setVisible(false);
}
});
t.setRepeats(false);
t.start();
}
});
dlg.setVisible(true);
Object n = MsgBox.getValue();
System.out.println(n);
System.out.println("Finished");
dlg.dispose();
}
}
make small frame like JOptionPane , show it in thread and dispose after 10 sec
精彩评论