问题
I am using JDBC to link my program to MySQL.
I noticed that establishing a connection to MySQL can take about 6-10 seconds. I want to use a JProgressBar to show the progress of the connection so that the user needen't think that my program crashed.
I tried inserting a simple print statement before and after the code. The print statement after the create connection printed only after 6-10 seconds.
I want to get progress between the connection.
Please I am not asking for you to do the full coding etc. Kindly tell me how I could acheive it?
回答1:
I think you can show an indeterminate JProgressBar
(see How to Use Progress Bar) since you can't exactly know the progress at a given time. Also use SwingWorker
to establish your connection at background avoiding to block EDT. Little code snippet:
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.setLocationRelativeTo(null);
final JProgressBar jProgressBar = new JProgressBar();
final JLabel status = new JLabel("Connecting...");
frame.add(status);
frame.add("jProgressBar", jProgressBar);
frame.pack();
frame.setVisible(true);
SwingWorker sw = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
jProgressBar.setIndeterminate(true);
Thread.sleep(6000); // Here you should establish connection
return null;
}
@Override
public void done(){
jProgressBar.setIndeterminate(false);
status.setText("Successful");
jProgressBar.setValue(100); // 100%
}
};
sw.execute();
}
And you'll see something like this:

回答2:
I don't think its possible to show real progress 'cause mysql connection process is just a tcp handshake and a couple of datagrams.
But you can show any kind of animation that indicates that the connection proceeds.
JProgressBar will not be updated until the corresponding paint event reaches its turn. So you should move connection routine to another thread if you didn't do yet.
If your print is a simple console print, it should work, I think. But if you print to some GUI component, it will not be updated at once.
回答3:
Use connection pooling. Grab the connections on the startup on your application and use a progress bar there.
At this part it should be easy to do that since you can just "block" until e.g. a flag becomes true (which means that you connections have been created) and it is more natural. Instead of showing progress bars as the user does something
来源:https://stackoverflow.com/questions/18671879/progress-bar-for-mysql-connection