I need to present a information message that needs to be in the screen for 5 seconds, during this time, user can't close the dialog. The specification says clearly that the dialog shouldn't have any button. Is there a way I can use JoptionPane.showMessageDialog in a way that the dialog have no button?
问题:
回答1:
How about this way using showOptionDialog
, maybe not showMessageDialog
, but the same thing when we have no buttons or place to enter text (downfall is it can be closed by user):
JOptionPane.showOptionDialog(null, "Hello","Empty?", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
UPDATE
Here is another way, it uses JOptionPane
and JDialog
(even better as it is uncloseable by user):
final JOptionPane optionPane = new JOptionPane("Hello world", JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[]{}, null);
final JDialog dialog = new JDialog();
dialog.setTitle("Message");
dialog.setModal(true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.pack();
//create timer to dispose of dialog after 5 seconds
Timer timer = new Timer(5000, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
dialog.dispose();
}
});
timer.setRepeats(false);//the timer should only go off once
//start timer to close JDialog as dialog modal we must start the timer before its visible
timer.start();
dialog.setVisible(true);
回答2:
Looks like David came up with something to satisfy your requirement of "No buttons".
Having said that, it sounds like you may need to clarify what are you real requirements. Is it really required that the dialog be un-closeable, or is that there is no button to close the dialog? JOptionPane and JDialog have a close button like a standard window.
回答3:
I dont think, that you could use a JOptionPane, because if i remember right, they always have one button at least. But you can use for example a splash panel like this or you can use a normal panel and run a thread in it. Like
public class TestFrame extends JFrame implements Runnabel{
private Thread thread;
private CallerClass c; //Class which built this frame
public TestPanel(CallerClass cc){
this.c = cc;
this.thread = null;
//Window can't be closed on (x)
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
//some things you put into your frame
//...
this.setVisible(true);
}
public synchronized void start(){
if (thread == null){
thread = new Thread(this);
thread.start();
}
@Override
public void run() {
try{
Thread.sleep(5000);
}catch(InterruptedException e){ }
this.setVisible(false);
this.c.destroyFrame();
this.stop();
}
}
Where destroyFrame() is e method in your class that build this panel to destroy it (set it to null or something) an you have to create this Frame with SwingUtilities.invokeLater(new TestFrame(this))
if you don't want the rest of your graphics to freeze.