Search code examples
javaswingactionlistener

How to change the function of a JFrame button?


I'm writing a program in NetBeans using JFrame that will use one button to connect and disconnect. When the client clicks the "Connect" button, an ActionListener creates a connection to the server. While connected, the button text changes from "Connect" to "Disconnect".

If the client clicks the button again, the connection needs to be closed. The specific commands I want to implement are pw.close(), br.close(), and mySocket.close().

If for any reason the client loses connection to the server, the button text will change back to "Connect" and clicking the button needs to re-establish the connection. This is what I have so far:

private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
       
        try {
        
        mySocket = new Socket(serverName.getText(), Integer.parseInt(port.getText())); //connect to server
        pw = new PrintWriter( mySocket.getOutputStream(), true ); //initialize printwriter
        br =  new BufferedReader( new InputStreamReader(mySocket.getInputStream() ) );//initialize buffered reader                  
        
        output.append("Connected to server\n");
        }
        catch (IOException e)
        {output.append("Connection Failed\n");
        }  
          
       if (mySocket.isConnected()){
            connectBtn.setText("Disconnect");

Solution

  • Use a JCheckBox or JToggleButton with a text of "Connected".

    Check the state of the box / button in the action listener to (if / else) take the appropriate action.