1

I have a button and Label on JFRAME. Clicking on button try to connect linux Server and this takes few second. I want to set the label text Connecting.. and Connected.But this doesn't set the label text Connecting .. during the button operation executing. Any Idea how to do that

private void buttonLConnectActionPerformed(java.awt.event.ActionEvent evt) {
    labelLOut.setText("Connecting");
    String ip="";
    String userid="username";
    String password="password";
Main_Window.LBoxconnect=new SshConnection(ip,userid,password);
    int x=LBoxconnect.checkConnection();
    if(x==1){
    labelLOut.setText("Connected");
    if(dx==1)
        buttonBTTInsert.setEnabled(true);
    else
        lx=1;
    }
    else
    labelLOut.setText("Connection Failed");
}  
mKorbel
  • 109,525
  • 20
  • 134
  • 319
cks
  • 83
  • 1
  • 2
  • 9

1 Answers1

0

You should do long actions in a background thread, not in a button listener, otherwise your UI will seem frozen.

In your listener, set the text to "Connecting" and then launch a thread wrapping your connection stuff. At the end of the runnable, update the text again once the long operation has finished.

Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • 1
    The answer here shows an example by using a swing worker: http://stackoverflow.com/questions/8916221/jlabel-will-not-update-unless-something-causes-the-method-to-hang – Moh-Aw Apr 09 '14 at 13:54
  • @Moh-Aw +1 nice link with explanations – Joffrey Apr 09 '14 at 13:57
  • Thanks,I'm trying to follow the suggested one. – cks Apr 09 '14 at 14:02
  • Resolved the problem using SwingWorker, Thanks a lot!! Some more useful link on Swing Worker http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html http://www.javacreed.com/swing-worker-example/ – cks Apr 10 '14 at 06:48