I am trying to use JavaFX
to code a stopwatch. But I am pretty new to java and still have problems to really understand OOP. I need to have to classes calling each others methods. I know that static methods and variables should be avoided.
The gui has buttons start and stop which should start and stop the timer. I have a "TimerClass"
set up. There is a method inside which runs code every second when it has been activated once. So when I hit the start button I want that to happen. This seems to work already. But every second the variable "secondsPassed"
is updated the label on my gui needs to be updated as well.
I could make the lblTime Button
and the corresponding method static.
Also I heard about about setting the constructors in a way that you can make every instance be equal to another existing instance. But I still do not understand it enough to be able to use it. (Java: classes with instance of each other)
I also tried creating a "helper class"
. This was to avoid having to instance two classes from one another. But the helper class would have still been another instance of "TimerClass"
.
I have some code to show what I have tried so far.
package application;
import application.TimerClass;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
public class Controller {
TimerClass timerClass = new TimerClass();
@FXML
Button btnStart;
@FXML
Button btnPause;
@FXML
Label lblTime;
public void btnStartAction() {
timerClass.timerStart();
}
public void btnPauseAction() {
timerClass.timerPause();
}
public void setLblTime(int input) {
lblTime.setText(""+input);
}
}
package application;
import application.Controller;
import application.Helper;
import java.util.Timer;
import java.util.TimerTask;
public class TimerClass {
static int secondsPassed = 0;
Controller controller = new Controller();
TimerClass timerClass = new TimerClass();
Helper helper;
public TimerClass(TimerClass input){
this.helper = timerClass;
}
public TimerClass() {
}
Timer mytimer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
secondsPassed++;
System.out.println("" + secondsPassed);
}
};
public void timerStart() {
mytimer.scheduleAtFixedRate(timerTask, 1000, 1000);
}
public void timerPause() {
mytimer.cancel();
}
public int getSecondsPassed() {
return secondsPassed;
}
}
Thanks in advance!