简体   繁体   中英

How to implement “Saving…” dialog box in Java?

I want to pop up a dialog box that says "Saving..." and once the operation is completed, it simply disappears. While the saving is in progress, I dont want the user to be able to do anything. I also dont want an OK button.

What is the name of the Java class that allows me to do this?

我认为JDialog是您想要的-请确保对其调用setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) ,因为与JFrame不同,其默认行为是HIDE_ON_CLOSE

Here's the final code I found that roughly simulated what I wanted to do:

// Create dialog box
JDialog dialog = new JDialog(new JFrame(), "Saving...");

// IMPORTANT: setLocationRelativeTo(null) is called AFTER you setSize()
// otherwise, your dialog box will not be at the center of the screen!
dialog.setSize(200,200);
dialog.setLocationRelativeTo(null);
dialog.toFront(); // raise above other java windows
dialog.setVisible(true);

// Sleep for 2 seconds
try
{
  Thread.sleep(2000);
} catch (InterruptedException ex)
{
  Logger.getLogger(JavaDialogBox.class.getName()).log(Level.SEVERE, null, ex);
}

// Then "close" the dialog box
dialog.dispose();

Lastly, found these 3 links to be quite helpful when writing the above code:

You might also consider using a javax.swing.JProgressBar within your dialog so you can show progress is happening. If you have enough information during the save process to give a percentage complete you can show that, and if not you can show it as indeterminate (moving back and forth until complete). Then dispose the dialog once the save process is complete -- this would be nice user experience enhancement over showing a static text message for a fixed amount of time. Here's a tutorial with demo Java code showing an example dialog: http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html .

I think what you may want is a modal JDialog . They make it fairly easy to block user interaction for your whole application and you have some extra control.

The code snippet you posted will potentially have issues if your save operation takes longer than 2 seconds. I'd suggest calling your save() function in the place where you currently have the Thread.sleep(). That way, you know that no matter how long the save takes, the UI will be blocked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM