简单地说,我有两个类,一个 GUI 类,它有一个按钮用于停止和运行另一个类/线程,用于从剪贴板获取文本内容并将其粘贴到文本文件中。但无论我尝试什么(例如使用 Swingworker),我都无法实现我的目标。该代码可以启动线程,但会卡住 GUI。我尝试使用 SwingWorker,但失败了。请告诉我一个解决方案。
class GUI
{
Thread a = null;
JButton onOffButton;
onOffButt.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if (a == null)
{
isOn = true;
onOffButt.setText("on");
onOffButt.setBackground(Color.green);
a = new Thread(new TextHandler());
a.start();
}
else
{
isOn = false;
onOffButt.setText("off");
onOffButt.setBackground(Color.red);
a.interrupt();
a = null;
}
}
});
}
class TextHandler() extends Thread
{
run()
{
for(;;)
{
// getClipboardContent();
// evaluate
// paste
}
}
}
最佳答案
在你的TextHandler
中,你做了什么事情,比如 sleep ,会捕获InterruptedException
吗?如果你不这样做,中断位将被提升,但你永远不会看到它。如果您没有做任何会注意到线程已被中断的事情,您可以将其添加到循环中:
for(;;)
{
// getClipboardContent();
// evaluate
// paste
if (Thread.currentThread().interrupted())
{
break;
}
}
关于java - 通过单击按钮启动和停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25002801/