how to display loading dialog at center of app screen?
I want to know how to display loading dialog at cent开发者_Python百科er of app screen. An indefinite progress bar.
If you're talking about a JDialog, after calling pack() on it, call setLocationRelativeTo(null) to center it.
Here's how I typically show a "loading..." progress bar. The loading itself must happen on a background thread to make sure the progress bar keeps updating. The frame with the progress bar will be shown in the center of the screen.
public static void main(String[] args) throws Throwable {
final JFrame frame = new JFrame("Loading...");
final JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true);
final JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.setLayout(new BorderLayout());
contentPane.add(new JLabel("Loading..."), BorderLayout.NORTH);
contentPane.add(progressBar, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Runnable runnable = new Runnable() {
public void run() {
// do loading stuff in here
// for now, simulate loading task with Thread.sleep(...)
try {
System.out.println("Doing loading in background step 1");
Thread.sleep(1000);
System.out.println("Doing loading in background step 2");
Thread.sleep(1000);
System.out.println("Doing loading in background step 3");
Thread.sleep(1000);
System.out.println("Doing loading in background step 4");
Thread.sleep(1000);
System.out.println("Doing loading in background step 5");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// when loading is finished, make frame disappear
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(false);
}
});
}
};
new Thread(runnable).start();
}
display loading dialog at center of app screen.
dialog.setLocationRelativeTo(...);
An indefinite progress bar.
Read the section from the Swing tutorial on How to Use Progress Bars
From the documentation:
JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true);
This will create the progress bar. To center it, you should take a look at the different kinds of layout managers in java. Without any examples of your existing code, it's hard to give a more precise answer to your question.
精彩评论