我想访问t.isStopped()
被覆盖的run()
方法,但出现以下错误。
不能在不同方法中定义的内部类中引用非最终变量 t
如果我将 t 设置为最终变量
局部变量 t 可能尚未初始化
<!-- language: java -->
jHibernateCheckBox = new JCheckBox("Sleep / Hibernate after ");
jHibernateTextField = new JTextField("240");
jHibernateCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StoppableThread t = new StoppableThread() {
@Override
public void run() {
t.setIsRunning(true);
long timestamp = new Date().getTime();
int minutes = Integer.parseInt(jHibernateTextField.getText());
long secounds = minutes * 60;
long millisecounds = secounds * 1000;
long elapsedTime = new Date().getTime();
do {
try {
Thread.sleep(1000);
millisecounds -= new Date().getTime() - elapsedTime;
secounds = millisecounds / 1000;
if(secounds < 60) {
jHibernateTextField.setText("" + secounds);
jRemainingLabel.setText(" secounds remaining");
}
else {
jHibernateTextField.setText("" + secounds / 60);
jRemainingLabel.setText(" minutes remaining");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
elapsedTime = new Date().getTime();
}while(!t.isStopped() && timestamp + minutes * 60 * 1000 > new Date().getTime());
jHibernateTextField.setText("" + minutes);
if(t.isStopped()) return;
else {
console.out("Computer wird schlafen gelegt =)");
//Hibernate (siehe LAPTOP)
}
}
};
Thread thread = new Thread(t);
if(jHibernateCheckBox.isSelected()) {
jHibernateTextField.setEnabled(false);
thread.start();
}
else {
jHibernateTextField.setEnabled(true);
t.setIsStopped(true);
}
}
});
是否可以访问内部类中的变量 t ,或者如果再次单击复选框,是否有人知道如何停止线程?
我只是希望当我再次单击 jHibernateCheckBox 时计时器停止工作......也许还有另一种方法?