Skip to content

Instantly share code, notes, and snippets.

Created August 9, 2016 16:20
Show Gist options
  • Save anonymous/aad1278a0ff779f0d516b66cadddbf67 to your computer and use it in GitHub Desktop.
Save anonymous/aad1278a0ff779f0d516b66cadddbf67 to your computer and use it in GitHub Desktop.
package timerexample;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TimerExample extends JFrame implements Observer, ActionListener {
TimerModel m;
long lastTime;
JLabel time;
JButton start, stop;
TimerExample() {
m = new TimerModel();
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
time = new JLabel();
String str = String.format("%02d:%02d", m.getTime() / 60, m.getTime() % 60);
time.setText(str);
time.setHorizontalAlignment(JLabel.CENTER);
time.setVerticalAlignment(JLabel.CENTER);
this.add(time, BorderLayout.CENTER);
start = new JButton("Start");
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m.start();
}
});
this.add(start, BorderLayout.WEST);
stop = new JButton("Stop");
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m.stop();
}
});
this.add(stop, BorderLayout.EAST);
lastTime = System.nanoTime();
Timer t = new Timer(20, this);
t.start();
}
@Override
public void setVisible(boolean b) {
super.setVisible(b);
//Observer reference added here to avoid reference leak in contructor
m.addObserver(this);
}
public static void main(String[] args) {
TimerExample x = new TimerExample();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
x.setSize(300, 200);
x.setVisible(true);
}
});
}
@Override
public void update(Observable o, Object arg) {
String str = String.format("%02d:%02d", m.getTime() / 60, m.getTime() % 60);
time.setText(str);
}
@Override
public void actionPerformed(ActionEvent e) {
long actual = System.nanoTime();
double diff = actual - this.lastTime - 1e9;
if (diff > -2.5e7) {
this.lastTime += 1e9;
System.out.println(actual + ",");
m.tic();
}
}
}
package timerexample;
import java.util.Observable;
public class TimerModel extends Observable {
int time = 600;
State s = new StatePause();
public void decrease() {
time--;
setChanged();
notifyObservers();
}
public int getTime() {
return time;
}
public void tic(){
s.tic();
}
public void start() {
s = new StateStart();
}
public void stop() {
s = new StatePause();
}
interface State {
void tic();
}
class StateStart implements State {
@Override
public void tic() {
decrease();
}
}
class StatePause implements State {
@Override
public void tic() {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment