Strange delay in modifying JPanel

Hi

Once the "Login" button is pressed, I want my JPanel to show the string "Connecting..." so I added a simple card panel to show either "Welcome" or "connecting...".

When the button is pressed, the code flows as expected, except that the card does not change until the Oracle database connection (from the checkUser method) returns. So basically, it only says "connecting..." after trying to connect. It's as if the JPanel/JFrame is not allowing any updates until the checkUser returns. checkUser just as a try block attempting to connect to a db.

Any ideas?

publicvoid actionPerformed(ActionEvent ae){

// char array to store the password

char[] charInputPassword;

// Set the Panel to show "Connecting..."

((CardLayout)cardPanel.getLayout()).show(cardPanel, CONNPANE);

// The text below appears in CMD window when logingButton button is pressed

// but the card panel doesn't not change until the checkUser

// procedure has completed. ?

TextIO.putln("Panel should now show CONNPANE");

if(ae.getSource() == loginButton){

inputUsername = usernameField.getText();

charInputPassword = passwordField.getPassword();

inputPassword =new String(charInputPassword);

TextIO.putln("OK Pressed - Username is " + inputUsername);

try{

checkUser();

}catch(Exception e){

TextIO.putln("CheckUser error: " + e.getMessage());

}

}

}

[2150 byte] By [fdgfda] at [2007-11-26 18:04:39]
# 1

Your action listener is invoked on the event dispatching thread, so until your method returns, that thread is blocked. In other words, by the time Swing gets a chance to update the GUI, it is too late.

An easy workaround is to wrap all the code following the modification of the GUI in a call to EventQueue.invokeLater(). Something like this:

public void actionPerformed(ActionEvent ae) {

// Set the Panel to show "Connecting..."

((CardLayout)cardPanel.getLayout()).show(cardPanel, CONNPANE);

...

if (ae.getSource() == loginButton) {

EventQueue.invokeLater(new Runnable() {

public void run() {

inputUsername = usernameField.getText();

charInputPassword = passwordField.getPassword();

inputPassword = new String(charInputPassword);

...

}

});

}

}

Geoff

glevnera at 2007-7-9 5:35:05 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thanks Geoff, I'll go away and read up on invokeLater() method.Much appreciated.
fdgfda at 2007-7-9 5:35:05 > top of Java-index,Desktop,Core GUI APIs...