简体   繁体   中英

Java: My JFrame's contents (buttons etc.) are not clickable when I start my server

I have created a simple HTTP server in Java by using a ServerSocket that accepts browser requests. The server is working fine without any errors. I have created a JForm using Swing that contains buttons to start and stop the server. In the start button I have added an ActionListener that runs my ServerMain class.

JButton btnStartServer = new JButton("Start Server");
    panel.add(btnStartServer);
    btnStartServer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                ServerMain.main(new String[0]);
                } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

Whenever i start the server though, my JFrame becomes unclickable, and so I cannot click the Exit button which contains this code:

JButton btnExit = new JButton("Exit");
    panel.add(btnExit);
    btnExit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                System.exit(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });;

The socket listening and accepting for connections through a loop must be the cause of this but I have no idea of how to fix it. Any suggestions would be brilliant. Thank you in advance :)

As Swing components are not thread safe, all UI actions are performed in special thread called Event Dispatcher Thread (EDT) (this technique called thread confinement ).

So you start ServerMain in EDT, that's why any subsequent actions will not perform.

To avoid such problem you should run blocking operations in separated thread. So rough solution to your problem:

btnStartServer.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        try {
            new Thread(new Runnable() {
                public void run() { 
                    ServerMain.main(new String[0]);
                }
             }).start();
            } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

I recommend you to read about Java concurrency , than you can read about concurrency model in Swing .

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