Search code examples
javaswingsocketsjoptionpanecancel-button

Handle java cancel button in two JOptionPane showInputDialog


First, i am sorry maybe the title is wrong. I will explain my problem. I have one joptionpane with showinputdialog component to input server address. I want after click Cancel button, it will return to main window. But in my case, it instead to second joptionpane.

My English is bad :) ... Anyone can help me ?

This is my code

    private static int setPortNumber()
{
    String portNumber = JOptionPane.showInputDialog(frame,
            "Enter the Port number for server creation","Server Connection\n",
            JOptionPane.OK_CANCEL_OPTION);
    int PORT = Integer.parseInt(portNumber);

    return PORT;

}   

private static String setServerName()
{   
    server_address = JOptionPane.showInputDialog(frame,
            "Enter Server Address or PC-Name.", "Server Connection",
            JOptionPane.OK_CANCEL_OPTION);
    return server_address;

}

private void networking() {
    server_address = setServerName();
        try {

            PORT = setPortNumber();
            if (server_address != null) {

                sock = new Socket(InetAddress.getByName(server_address) ,
                        PORT);
            } 
            else {
                SocketException sc = new SocketException();
                throw sc;
            }


        // Recieving input and output streams
        InputStreamReader ir = new InputStreamReader(sock.getInputStream());
        br = new BufferedReader(ir);
        pw = new PrintWriter(sock.getOutputStream());
        login.setEnabled(true);
        incoming.append("Connected to Server.please login.\n");
        connect.setEnabled(false);
        pw.println("~##~");
        pw.flush();
        login.requestFocus();
    }

Solution

  • private void networking() {
        server_address = setServerName();
        if(server_address == null || server_address.equals("")){
            //Handle what happens when the server name is empty (or the user clicked the cancel button. If you let the execution continue, then the try/catch block below will pop up the second jInputDialog
        }
            try {
    
                PORT = setPortNumber();
                if (server_address != null) {
    
                    sock = new Socket(InetAddress.getByName(server_address) ,
                        PORT);
                } 
                else {
                    SocketException sc = new SocketException();
                    throw sc;
                }
    ...
    }