i wrote an Application of a simple counter, nothing more. My GUI has a Label and 1 Button for the start/stop function. My EventHandler of the button looks like this:
b_start.setOnAction((ActionEvent e) ->{
if(!clock.isRunning()){
clock.setRunning(true);
b_start.setText("Stop");
b_start.setStyle("-fx-background-color: red");
}else{
clock.setRunning(false);
b_start.setText("Start");
b_start.setStyle("-fx-background-color: lightgreen");
}
});
--Clock.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
import java.util.Observable;
/**
*
* @author
*/
public class Clock extends Observable implements Runnable {
private String zeit = "";
private int sek;
private boolean isRunning = false;
public Clock() {
}
public void setZeit() {
zeit = "" + sek;
}
public String getZeit() {
return zeit;
}
public void setRunning(boolean running){
this.isRunning = running;
}
public boolean isRunning(){
return isRunning;
}
public int getSek() {
return sek;
}
@Override
public void run() {
while (true) {
System.out.println();
if (isRunning()) {
try {
sek++;
setZeit();
System.out.println();
this.setChanged();
this.notifyObservers();
Thread.sleep(1000);
} catch (InterruptedException ex) {
//TODO
}
}
}
}
}
Right now, this code isnt working. Seems like the if()- clause isnt reachable but isRunning() returns "true".. (Tested with System.out.println)
Another way:
@Override
public void run() {
while (true) {
System.out.println(); //ADDING THIS -> CODE WORKS //DELETE THIS -> //CODE WONT WORK
if (isRunning()) {
try {
sek++;
setZeit();
this.setChanged();
this.notifyObservers();
Thread.sleep(1000);
} catch (InterruptedException ex) {
//TODO
}
}
}
}
Why do i have to make the isRunning method synchronized//Why can i add a simple System.out.println() to make the code do what it has to?