0

我有一个 jframe 和 jtextpane,我想运行一个在 pc 中检查端口的方法,直到用户关闭 jframe,我正在尝试使用 windowlistner 但该方法只运行一次,我希望它一直运行到用户关闭应用程序

frame = new JFrame();

        frame.setResizable(false);
        frame.setBounds(100, 100, 552, 444);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        frame.addWindowListener(new WindowListener() {

            @Override
            public void windowOpened(WindowEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowIconified(WindowEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowDeiconified(WindowEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowDeactivated(WindowEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowClosing(WindowEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowClosed(WindowEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowActivated(WindowEvent arg0) {
                checkport(); // this run at first time only!

            }
        });
4

1 回答 1

1

您应该使用单独的线程来检查在显示框架时启动的端口。在 windowClosing 事件中,您停止线程。

示例代码:

    frame = new JFrame();
    frame.setResizable(false);
    frame.setBounds(100, 100, 552, 444);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    final CheckPort checkPort = new CheckPort();
    final Thread thread = new Thread( checkPort );
    thread.start();
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing( WindowEvent e ) {
            checkPort.stop();
            thread.interrupt();
        }
    });

可运行以检查端口。

    public class CheckPort implements Runnable {
        private boolean checkPort = true;

        public void run() {
            while( checkPort ) {
                checkPort();
                try {
                    Thread.sleep( 100 );
                } catch( InterruptedException ex ) {
                }
            }
        }

        public void checkPort() {
            // do check port here
        }

        public void stop() {
            checkPort = false;
        }
    }
于 2013-02-20T14:40:23.797 回答