import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class SleeperFrame extends JFrame {
private static final long serialVersionUID = 2685140782562499729L;
private Sleeper sleeper = new Sleeper();
public SleeperFrame() throws InterruptedException {
super("SleeperFrame");
this.setLayout(new GridLayout(2,1));
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
JButton wakeup = new JButton("Wake me up.");
wakeup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
SleeperFrame.this.sleeper.wakeup();
SleeperFrame.this.dispose();
}
});
this.add(new JLabel("You have 10 seconds to wake me up!"));
this.add(wakeup);
this.pack();
this.setVisible(true);
sleeper.start();
// ich weiß schon, das is unsauber aber es dient ja auch nur zur Veranschaulichung beider Fälle
Thread.sleep(10000);
sleeper.interrupt();
this.dispose();
}
public static void main(String[] args) throws InterruptedException {
new SleeperFrame();
}
}
class Sleeper extends Thread {
private boolean _sleep = true;
public void wakeup() {
this._sleep = false;
this.interrupt();
}
@Override
public void run() {
try{
while(this._sleep )
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
;
} finally {
if (this._sleep)
JOptionPane.showMessageDialog(null,"Automatic wakeup initiated: you fail ^^","Error",JOptionPane.ERROR_MESSAGE);
else
JOptionPane.showMessageDialog(null,"Everything is ok.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
}