Question

I have two simple applications to shutdown, restart, and log off the client computer remotely, what i'm facing is that when client connect to server, the Jlabel component (statuslabel) is no longer editable until the connection is terminated (By closing server app) i tried lots of things, like using socket.isConnected method .. but with no result. Here's the client code:

package homework_5.client;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import javax.swing.JOptionPane;

/**
 *
 * @author حسين
 */
public class ClientSideGUI extends javax.swing.JFrame {
Socket socket=null;
String status;
String recievedCommand;
BufferedReader in=null;
Process child;
 /**
 * Creates new form ClientSide
 */
public ClientSideGUI() {
    initComponents();

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    statuslabel = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Client.");
    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowOpened(java.awt.event.WindowEvent evt) {
            formWindowOpened(evt);
        }
    });

    statuslabel.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
    statuslabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addComponent(statuslabel, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(20, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(55, Short.MAX_VALUE)
            .addComponent(statuslabel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(53, 53, 53))
    );

    pack();
}// </editor-fold>

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  

    try{
          socket=new Socket("127.0.0.1", 1234);
          status="Online";
       }catch(Exception e){status="Offline";}


    //Display status @حسين

                     if(status.equals("Online"))
                     {
                     statuslabel.setForeground(Color.GREEN);
                     statuslabel.setText(status);
                     }
                     if(status.equals("Offline"))
                     {
                     statuslabel.setForeground(Color.RED);
                     statuslabel.setText(status);
                     }


   //Getting the work done :) @حسين
              {
                    while(status.equals("Online"))
                    {
                    try{
                    in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    recievedCommand=in.readLine();
                       }catch(IOException e2){JOptionPane.showMessageDialog(rootPane,"Connected to server,\n but facing problems with recieving command\n Exception:"+e2.getClass().getName());}




                    if(recievedCommand.equals("shutdown -s"))
                        {try{    
                             child=Runtime.getRuntime().exec(recievedCommand);
                             }catch(Exception e3){JOptionPane.showMessageDialog(rootPane, "Command Recieved but an error occured on local execution.\n Exception:"+e3.getClass().getName());}
                        }

                    if(recievedCommand.equals("shutdown -r"))
                        {try{    
                             child=Runtime.getRuntime().exec(recievedCommand);
                             }catch(Exception e4){JOptionPane.showMessageDialog(rootPane, "Command Recieved but an error occured on local execution.\n Exception:"+e4.getClass().getName());}
                        }

                    if(recievedCommand.equals("shutdown -l"))
                        {try{    
                             child=Runtime.getRuntime().exec(recievedCommand);
                             }catch(Exception e5){JOptionPane.showMessageDialog(rootPane, "Command Recieved but an error occured on local execution.\n Exception:"+e5.getClass().getName());}
                        }



                    }

              }



 }                                 

 /**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ClientSideGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ClientSideGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ClientSideGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ClientSideGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ClientSideGUI().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
public javax.swing.JLabel statuslabel;
// End of variables declaration
}
Was it helpful?

Solution

Your Socket connection is blocking the Event Dispatch Thread(EDT) so the GUI can't repaint itself. You need to create a separate Thread to do the Socket connection.

Read the section from the Swing tutorial on Concurrency for more information and a solution that uses a Swing Worker.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top