I obviously am having problems with my understanding of interfaces/ listeners in Java. (Java newbie alert at red). Using https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html and interface examples, I am getting behaviour I do not understand from timer.stop, and/ or removing actionlisteners from the timer (I.e. firing the 'tick'). Whatever I do, I cannot stop the timer when using an interface etc- I can only get it to work in local classes = spaghetti code.
public void actionPerformed(ActionEvent e) {
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
JButton clicked= (JButton) e.getSource();
ClockLabel mainsClockList= new ClockLabel(mainsLab);
if (clicked==clock1But) {
///////// Clock not started
if (mainsRunning==false) {
//mainsClockList = new ClockLabel(mainsLab); // that starts
// it, wait for FB in listnr
mainsClockList.setStopWatchListener(new StopWatchListener() {
public void clockCount(long count) {
System.out.println("Clock fired"); // fired every
//click- should only be on attach
// multiple calls button or EL?
mainsLab.setText(sdf.format(count));
}
});
clock1But.setText("Stop");
mainsRunning=true;
}
//// clock already started
else if (mainsRunning== true) {
System.out.println("in butt pressed already run");
mainsClockList.stopClock();
mainsClockList.setEnabled(false);
mainsRunning=false;
}
}
else if (clicked==clock2But) {
System.out.println("Got 2nd but"); }
else if (clicked==clock3But) {
System.out.println("Got 3rd but"); }
}
the Clock Lab class stuff:-
public ClockLabel(JLabel labIn) {
sdf = new SimpleDateFormat("mm:ss");
t= new Timer(500, this );
t.start();
}
public void actionPerformed(ActionEvent e) {
// this is listener for t....
Date d= new Date();
long diff= d.getTime() -cStarted.getTime();
swListener.clockCount(diff);
}
public void stopClock() {
System.out.println("In CL, called stopclock");
t.stop(); // no effect
swListener= null; // no effect
System.out.println("swListener := null");
// swListener.wait(5000); null pointer on try catch so
//has killed sw....!
}
public void setStopWatchListener(StopWatchListener listener) {
this.swListener= listener;
}
}
Interface
public interface StopWatchListener {
public void clockCount(long count);
}
I have tried to minimise code but keep comments in to help. Thanks for any pointers, much appreciated. System out is as follows with only 1 click on button to start, and one to stop:
Clock fired Clock fired Clock fired Clock fired in butt pressed already run In CL, called stopclock swListener := null Clock fired Clock fired Clock fired Clock fired