I want to create seconds arrow with Line
object. On button click arrow should start spinning in a circle in other Thread
. The program not responding while calculating current rotate position. How to do this correctly?
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.shape.Line?>
<Pane fx:id="rootPane" focusTraversable="true" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onKeyPressed="#startSecondsLine" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<Line fx:id="secondsLine" endX="60.0" layoutX="300.0" layoutY="200.0" startX="-100.0" strokeWidth="2.0" />
<Label layoutX="14.0" layoutY="14.0" text="Start(X, Y):" />
<Label layoutX="14.0" layoutY="31.0" prefHeight="17.0" prefWidth="63.0" text="End(X, Y):" />
<Label fx:id="startXY" layoutX="77.0" layoutY="14.0" prefHeight="17.0" prefWidth="63.0" />
<Label fx:id="endXY" layoutX="77.0" layoutY="31.0" prefHeight="17.0" prefWidth="63.0" />
<Button layoutX="15.0" layoutY="48.0" mnemonicParsing="false" onAction="#startTimer" text="Start" />
</children>
</Pane>
Controller:
package sample;
import java.net.URL;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.shape.Line;
import javafx.event.ActionEvent;
public class Controller {
@FXML
private Line secondsLine;
@FXML
private Label startXY;
@FXML
private Label endXY;
@FXML
void startTimer(ActionEvent event) {
MyThread myThread = new MyThread(secondsLine);
myThread.run();
}
@FXML
void initialize() {
startXY.setText("(" + secondsLine.getStartX() + ", " + secondsLine.getStartY() + ")");
endXY.setText("(" + secondsLine.getEndX() + ", " + secondsLine.getEndY() + ")");
}
}
MyThread class
package sample;
import javafx.scene.shape.Line;
public class MyThread extends Thread {
private Line line;
@Override
public void run() {
System.out.println(line + " from other thread.");
try {
rotateLine();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public MyThread(Line line) {
this.line = line;
}
public void rotateLine() throws InterruptedException {
int circle = 0;
System.out.println("Start of circle;");
do {
sleep(1000);
line.setRotate(circle);
circle += 6;
} while (circle < 360);
System.out.println("End of circle;");
}
}