简体   繁体   English

Java:启动服务器时,无法单击我的JFrame的内容(按钮等)

[英]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. 我通过使用接受浏览器请求的ServerSocket在Java中创建了一个简单的HTTP服务器。 The server is working fine without any errors. 服务器运行正常,没有任何错误。 I have created a JForm using Swing that contains buttons to start and stop the server. 我使用Swing创建了一个JForm,其中包含用于启动和停止服务器的按钮。 In the start button I have added an ActionListener that runs my ServerMain class. 在开始按钮中,我添加了一个运行ServerMain类的ActionListener。

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: 但是,无论何时启动服务器,我的JFrame都变得不可单击,因此无法单击包含以下代码的“退出”按钮:

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 ). 由于Swing组件不是线程安全的,因此所有UI操作都在称为事件分派器线程 (EDT)的特殊线程中执行(此技术称为线程限制 )。

So you start ServerMain in EDT, that's why any subsequent actions will not perform. 因此,您在EDT中启动ServerMain ,这就是为什么任何后续操作都不会执行的原因。

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 . 我建议您阅读有关Java 并发的知识 ,而不是阅读有关Swing中的并发模型的知识

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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