简体   繁体   中英

Java JButton and swing problem

I am doing a networking project. I compiled a code under Java Project console app and it works. But when I create a GUI and assign the code to run when a button is pressed, it hangs on clicking the button.

This is the source code:

@Action
public void EstablishConnection() {
    serverAddress = jTextFieldServerAddress.getText();
    serverPort = Integer.parseInt(jTextFieldPort.getText());
    serverUName = jTextFieldUName.getText();
    serverUPwd = jTextFieldUPwd.getText();

    try {
        client = new FTPClient();

        client.connect(serverAddress, serverPort);   
        boolean login = client.login(serverUName, serverUPwd);

        if(login) {
            System.out.println("Successfully logged in\n");
        }
        else {
            System.out.println("Unable to login\n");
        }
    } 
    catch(Exception ex) {
        System.out.println("Exception Raised: " + ex);
    }
}

The action is called when a button is pressed in the swing app. It is not working for me. But it is working very fast for a console app.

Anytime I see the word "hang" I assume you need to be using a separate Thread to execute the hanging code. See Concurrency in Swing for the solution.

I would suggest that you should run code that depends on external factors, like accessing a remote server etc., that could delay the response, in a thread of it's own.

Display a MessageDialog with an indeterminate progress bar:

connProgressBar.setIndeterminate(true);

You neither know whether your connection will terminate, nor if it will, so add a button that allows the user to kill the connection thread, whenever she feels like it.

Since you are probably connecting to an ftp server in order to upload and download files, after the connection has been established, use a determinate progressbar that shows the download percentage of the file or files progress, that runs in a new thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM