我有一个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!
}
});
答案 0 :(得分:1)
您应该使用Separate Thread检查显示Frame时启动的端口。在windowClosing Event上你停止线程。
示例代码:
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();
}
});
用于检查端口的Runnable。
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;
}
}