Reputation: 96016
I wrote a program that shows a JFrame
containing an information about the machine that runs it (HOST
and IP
) and it make JDBC
connection to display another information.
I have only these two lines in my main
function:
NewFrame nf = new NewFrame(); //Here I make all the needed calculations
nf.setVisible(true);
(NewFrame extends JFrame)
In the constructor I perform all needed calculations and set them to be shown in the nf JFrame
.
When I run the program, I see the border of the JFrame
for 0.5-1 seconds before it get filled with the information, although I set it to be visible only after constructing it.
This is what I see for about 1 second: (The inside is my desktop background)
and then I see the information:
Why this happens although I make all the calculations in the constructor?
Upvotes: 1
Views: 455
Reputation: 13900
Looks like you do some blocking call, i.e. database query, in GUI thread synchronously. You should do such things asynchronously using SwingWorker
:
final JTextField field = new JTextField ();
field.setEditable (false);
JButton button = new JButton(new AbstractAction ("Calculate!") {
@Override
public void actionPerformed(ActionEvent e) {
field.setText ("Calculating...");
new SwingWorker<String, String> ()
{
@Override
protected String doInBackground() throws Exception {
Thread.sleep(3000L);
field.setText ("Calculated!");
return null;
}
}.execute();
}
});
JFrame frame = new JFrame ();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane ().setLayout (new BorderLayout());
frame.getContentPane ().add (button, BorderLayout.NORTH);
frame.getContentPane ().add (field, BorderLayout.CENTER);
frame.pack ();
frame.setVisible (true);
Upvotes: 1
Reputation: 347332
Sounds like you're blocking the event dispatching thread (EDT)
You should avoid running any operation that might block or is time consuming on the EDT. This will prevent the EDT from dispatching repaint events, which are kind of important.
You might like to take a look at Concurrency in Swing and probably Swing Worker
One of the important rules when dealing with Swing and Threads, you must only interact with Swing components from inside the EDT
Upvotes: 5