Adding a message box to a Java program that opens and closes at a certain point
I was able to figure out getting input from the user and displaying the final product by myself, but I would like to add a "busy" message that displays at a certain point and then closes at a certain point in the code.
Hopefully it'll be easier to explain by showing it in my code. It's for a sorting algorithm and the sorting times obviously will vary.
public static void main(String[] args) throws Exception{
//Code that doesn't matter for this question...
String userInput = JOptio开发者_C百科nPane.showInputDialog("Please enter the amount of input you would like to test (integer): ");
// Code that doesn't matter for this question....
//
// Open dialogue box here that says, "Busy sorting" and stays open
//
long startTime = System.currentTimeMillis();
sort(shorts);
long endTime = System.currentTimeMillis();
//
// The dialogue box closes here without the user having to press anything
//
// This displays the final output.
JOptionPane.showMessageDialog(null, error + "The runtime for " + input + " short integers is " + (endTime-startTime) + " milliseconds.", "Final Runtime", JOptionPane.PLAIN_MESSAGE);
}
Hopefully the question is understandable.
What you will need is to use the SwingWorker
class to run your long task on a separate thread from the GUI. While this is running displaying a JProgressBar
or something similar would be ideal.
http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html
The JFrame is probably what you are looking for.
Ah yes, and keep in mind the important remark on threading in Swing by jzd. You'll want to read up on that too.
Read the section from the Swing tutorrial on How to Use Progress Bars for some examples.
Or maybe you would like to try using a Disabled Glass Pane.
I will probably not use JOptionPane. Since while displaying the busy message, the program will not be executing. You better create a more elaborate swing application with a text field and a button. When the user click on the button, the system display a busy message on the bottom of the windows.
As I mentioned in my question, you should check out the swing tutorial. It's really good, and really easy to follow.
JOptionPane is part of Java Swing, though, as others have said, it's probably not the best approach for displaying a busy state. As others have said, a progress bar might be a good option, depending on your needs, but you'll see other options when you go through the tutorial.
Good Luck!
精彩评论