stop for X seconds before running next function in JAVA FXML (using SCENEBUILDER) - javafx

I've used Scenebuilder to place few shapes in my GUI (simplified version of my project). I would like the shapes to change colours but wait 2 seconds between changing colours. I want these changes to happen in my controller class after a button is pressed.
Circle1.setFill(YELLOW)
Wait(2 seconds)
Circle2.setFill(BLUE)
I'm not sure how to do that. I have read online about threading, but I don't really understand how to implement that from my Main and into my Controller class. Also, I could not really find any examples online. My Main class looks like:
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("File.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
}
Please help. Also, if you could provide an example would be helpful for me to understand as I could not really find one online that gives an example of this.

Answering this question is easiest through an example I believe. So I've created a small Traffic Light application, since it allows me to use Circle and a timed sequence similar to your problem, whilst being a familiar concept for all.
I'll be using java.util.Timer alongside java.util.TimerTask for handling the sequence of lights. You may choose to use some animation / time line in JavaFX, but I think that is overkill for this kind of task.
I include the three files used in this project:
FXMLTrafficLight.fxml - which defines my FXML layout
FXMLTrafficLightController.java - my FXML controller
TrafficLightApplication.java - for completeness my subclass of Application, this is just the boiler plate.
FXMLTrafficLight.fxml
Not a fancy layout, just a VBox with three circles redLight, amberLight and greenLight, plus two Button objects startLights and stopLights used to start and stop the timer.
<VBox fx:id="root" id="VBox" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxtimer.FXMLTrafficLightController">
<children>
<Circle fx:id="redLight" radius="100"></Circle>
<Circle fx:id="amberLight" radius="100"></Circle>
<Circle fx:id="greenLight" radius="100"></Circle>
<Button fx:id="startLights" text="Start Lights" onAction="#startLights"></Button>
<Button fx:id="stopLights" text="Start Lights" onAction="#stopLights"></Button>
</children>
</VBox>
FXMLTrafficLightController.java
I've included the model/state in the controller for simplicity. Whether a light is red / amber / green is determined by a boolean flag. The initial state is set in the initialize() method, and is updated by calling updateState().
When startLights(ActionEvent) is invoked (the EventHandler for startLights) a new Timer is constructed with a TimerTask implementation that first invokes updateState() on the thread created by the Timer and then invokes updateLights() which changes the color of the lights based on the current state on the JavaFX Application Thread using Platform.runLater(Runnable).
Note: the TimerTask itself will not be run on the JavaFX Application Thread, hence the need to use Platform.runLater(Runnable) for updating the GUI.
When stopLights(ActionEvent) is invoked, it will cancel the Timer.
Note that both startLights(ActionEvent) and stopLights(ActionEvent) toggle which Button objects are enabled on the interface as well.
public class FXMLTrafficLightController implements Initializable {
#FXML
private Circle redLight;
#FXML
private Circle amberLight;
#FXML
private Circle greenLight;
#FXML
private Button startLights;
#FXML
private Button stopLights;
private Timer timer;
private static final int DELAY = 2000; // ms
private boolean red, amber, green;
#Override
public void initialize(URL url, ResourceBundle rb) {
red = true;
amber = false;
green = false;
stopLights.setDisable(true);
updateLights();
}
#FXML
private void startLights(ActionEvent e) {
toggleButtons();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Not run on the JavaFX Application Thread!
updateState();
// Using Platform.runLater(Runnable) to ensure updateLights()
// is run on the JavaFX Application Thread
Platform.runLater(new Runnable() {
#Override
public void run() {
updateLights();
}
});
}
}, 0, DELAY); // no initial delay, trigger again every 2000 ms (DELAY)
}
#FXML
private void stopLights(ActionEvent e) {
toggleButtons();
timer.cancel();
}
private void toggleButtons() {
startLights.setDisable(!startLights.isDisable());
stopLights.setDisable(!stopLights.isDisable());
}
private void updateState() {
if (red && !amber && !green) {
amber = true;
} else if (red && amber && !green) {
red = false;
amber = false;
green = true;
} else if (!red && !amber && green) {
green = false;
amber = true;
} else {
red = true;
amber = false;
green = false;
}
}
private void updateLights() {
redLight.setFill(red ? Color.RED : Color.GREY);
amberLight.setFill(amber ? Color.ORANGE : Color.GREY);
greenLight.setFill(green ? Color.GREEN : Color.GREY);
}
}
TrafficLightApplication.java
For completeness... Just the standard boiler plate with file names changed.
public class TrafficLightApplication extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLTrafficLight.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Related

JavaFX KeyEvent doesn't do anything

So I have a little program where you can fly your spaceship between planets and I want to use the arrow keys to rotate the ship. First I tried adding the key listener to the panel and the ship did rotate, but only when I pressed ctrl/alt. Then I tried adding the key listener to the scene instead (which people say is the right thing to do because it doesn't depend on focus), but although the function that rotates the ship is called, you can't see anything on the screen.
The main class:
#Override
public void start(Stage stage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root, 700, 500);
Controller controller = new Controller();
loader.setController(controller);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
stage.setScene(scene);
stage.setFullScreen(true);
stage.show();
controller.setScene(scene);
} catch(Exception e) {
e.printStackTrace();
}
}
The controller:
#FXML
private BorderPane contentPane;
private OrbiterPanel orbiterPanel = new PerfectCirclePanel(this);
private Scene scene;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
contentPane.setCenter(orbiterPanel);
}
public void setScene(Scene scene) {
this.scene = scene;
scene.addEventFilter(KeyEvent.KEY_PRESSED, e -> keyStrokesPressed(e));
scene.addEventFilter(KeyEvent.KEY_RELEASED, e -> keyStrokesReleased(e));
}
private void keyStrokesPressed(KeyEvent e) {
switch(e.getCode()) {
case LEFT -> {
orbiterPanel.leftPressed();
}
case RIGHT -> {
orbiterPanel.rightPressed();
}
default -> {}
}
}
private void keyStrokesReleased(KeyEvent e) {
switch(e.getCode()) {
case LEFT -> {
orbiterPanel.leftReleased();
}
case RIGHT -> {
orbiterPanel.rightReleased();
}
default -> {}
}
}
The superclass of all my "worlds/maps":
protected AtomicReference<Spaceship> shipReference = new AtomicReference<>();
protected RotateTransition rotatingTransition;
public OrbiterPanel() {
rotatingTransition = new RotateTransition();
rotatingTransition.setCycleCount(RotateTransition.INDEFINITE);
rotatingTransition.setInterpolator(Interpolator.LINEAR);
}
protected void rightPressed() {
if(rotatingTransition.getStatus().equals(Status.RUNNING)) return;
rotatingTransition.stop();
rotatingTransition.setNode(shipReference.get());
rotatingTransition.setByAngle(360);
rotatingTransition.setDuration(Duration.seconds(2));
rotatingTransition.play();
}
protected void leftPressed() {
if(rotatingTransition.getStatus().equals(Status.RUNNING)) return;
rotatingTransition.stop();
rotatingTransition.setNode(shipReference.get());
rotatingTransition.setByAngle(-360);
rotatingTransition.setDuration(Duration.seconds(2));
rotatingTransition.play();
}
protected void rightReleased() {
rotatingTransition.stop();
}
protected void leftReleased() {
rotatingTransition.stop();
}
PerfectCirclePanel, a subclass of OrbiterPanel doesn't really do much besides displaying the spaceship and a planet.
FXML:
<BorderPane prefHeight="607.0" prefWidth="877.0" xmlns="http://javafx.com/javafx/17" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
<center>
<BorderPane fx:id="contentPane" prefHeight="704.0" prefWidth="963.0" style="-fx-background-color: black;">
</BorderPane>
</center>
</BorderPane>
There are two different ways to connect a controller to the UI defined by an FXML file.
Either:
Specify the controller class by providing a fx:controller attribute to the root element of the FXML. In this case, by default, a controller instance will be created from that class by invoking its no-argument constructor, and that instance will be the controller associated with the UI.
Or:
Call setController(...) on the FXMLLoader instance.
When you call loader.load(), if a controller exists, any #FXML-annotated fields in the controller will be initialized from the corresponding FXML elements, and then the initialize() method will be called.
In your code, you create two Controller instances: one is created from the fx:controller attribute, and associated with the UI. The other you create "by hand" in the Java code. The latter is not connected to the UI (the #FXML-annotated fields are not injected, and initialize() is not invoked), because you call setController(...) after calling load().
Because there are two Controller instances, there are two OrbiterPanel instances. The one created from the fx:controller attribute is the one displayed in the UI (because that's the one referenced when initialize() is invoked). The one created from the Controller instance you create in code is not displayed; however that is the one referenced by your event handler.
Remove the fx:controller attribute, and move the call to setController() before the call to load().

JavaFX2 play wav in background

So I'm trying to play indefinitly a song on a background thread, but when the music ends it does not loop as it was supose to.
Tried the offered solution but yet no joy! Here is the code for the main class, hope this helps in the resolution of the issue.
Even tried to loop the thread, but no joy...
Not sure why it's ending after playing the full file once, but not sure how to solve it!
Here is the code I have. Any help is welcome
public class Main extends Application {
Media sugar = new Media(this.getClass().getResource("sounds/t1coSugar.wav").toExternalForm());
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(Main.class, args);
}
#Override
public void start(Stage primaryStage)
{
primaryStage.setTitle("pacman");
primaryStage.setWidth(MazeData.calcGridX(MazeData.GRID_SIZE_X + 2)); //stage size x
primaryStage.setHeight(MazeData.calcGridY(MazeData.GRID_SIZE_Y + 5)); //stage size y
//splash screen
//end of splash screen
final Group root = new Group();
final Scene scene = new Scene(root);
root.getChildren().add(new Maze());
primaryStage.setScene(scene);
primaryStage.show();
int playbackgroundmusic = playbackgroundmusic();
}
private int playbackgroundmusic()
{
Runnable task = new Runnable() {
#Override
public void run() {
playSugar(); //method of the music
}
};
// Run the task in a background thread
Thread backgroundThread = new Thread(task);
// Terminate the running thread if the application exits
backgroundThread.setDaemon(true);
// Start the thread
backgroundThread.start();
return 0;
}
public void playSugar()
{
MediaPlayer mediaplayer = new MediaPlayer(sugar);
mediaplayer.volumeProperty().setValue(0.4);
mediaplayer.setStartTime(Duration.seconds(0));
mediaplayer.setStopTime(Duration.seconds(67));
mediaplayer.setAutoPlay(true);
mediaplayer.setCycleCount(MediaPlayer.INDEFINITE);
mediaplayer.play();
}

How do i update a textfield in javafx in loop ?

I have a small javafx application using scene builder which on a button click should read a string from COM port at regular intervals and update in a text field.
But now it only shows the last string if I use a for loop, and nothing if i put the code in infinite loop (That's my temporary requirement).
Can anyone help me so that at each read from COM port the new string is updated in the text field.
Here is the code I used for both the cases :
Note : In both cases in controller class, I'm getting perfect output on console.
public class Main extends Application
{
#Override
public void start(Stage primaryStage)
{
try
{
Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
Scene scene = new Scene(root);
//scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("test");
primaryStage.setScene(scene);
primaryStage.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
launch(args);
}
}
Here is the Controller class :
// In this case it shows only the last string in the text field.
public class Controller implements Initializable
{
#FXML
private Button sayHelloButton;
#FXML
private TextField helloField;
#Override
public void initialize(URL arg0, ResourceBundle arg1)
{
}
#FXML
public void printHello(ActionEvent event)
{
if(event.getSource() == sayHelloButton)
{
SerialPort serialPort = new SerialPort("COM22");
for(int i=0;i<5;i++)
{
try
{
if(!serialPort.isOpened())
{
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
}
String str = serialPort.readString(10,3000);
System.out.println(str);
helloField.clear();
helloField.setText(str);
}
catch(Exception e)
{
helloField.setText(e.toString());
}
}
}
}
}
Here is the method with infinite loop :
//this shows nothing in the text field
#FXML
public void printHello(ActionEvent event)
{
if(event.getSource() == sayHelloButton)
{
SerialPort serialPort = new SerialPort("COM22");
while(true)
{
try
{
if(!serialPort.isOpened())
{
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
}
String str = serialPort.readString(10,3000);
System.out.println(str);
helloField.clear();
helloField.setText(str);
}
catch(Exception e)
{
helloField.setText(e.toString());
}
}
}
}
There are a couple things happening here. In your first example, you state that the console output is correct but the TextField only shows the last result.
This is expected if the loop executes quickly. The TextField is being updated, but it happens so quickly that you can't see it until the loop ends and the last result is still being displayed. Even if you have a delay built into the loop, this could still block the UI from being updated until the loop is completed.
With your infinite loop, the issue is that the loop is being run on the JavaFX Application Thread (JFXAT). This blocks any updates to the GUI until the loop is finished, which is never is.
You will need to move the infinite loop to a new background thread. From there, you can update the GUI using the Platform.runLater() method.
SerialPort serialPort = new SerialPort("COM22");
new Thread(() -> {
while(true)
{
try
{
if(!serialPort.isOpened())
{
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
}
String str = serialPort.readString(10,3000);
System.out.println(str);
// Update the UI on the JavaFX Application Thread
Platform.runLater(() -> {
helloField.clear();
helloField.setText(str);
});
}
catch(Exception e)
{
Platform.runLater(() -> helloField.setText(e.toString()));
}
}
}).start();
This allows your UI to continually update as the background thread sends it new information.

Why does my JavaFX Preloader occasionally show up gray/black and other times it correctly loads?

I'm trying to get my JavaFX Preloader splash sccreen to show up before my application. I'm using Eclipse IDE and when I click "run", half the time the splash screen will display correctly and the other half of the time I will get a gray or black screen instead of where the image should be.
I'm not sure what the issue is to cause it to only display correctly sometimes.
SplashController:
public class SplashController extends Preloader {
private static final double WIDTH = 676;
private static final double HEIGHT = 227;
private Stage preloaderStage;
private Label progressText;
private Pane splashScreen;
public SplashController() {}
#Override
public void init() throws Exception {
ImageView splash =
new ImageView(new Image(Demo.class.getResource("pic.png").toString()));
progressText =
new Label("VERSION: " + getVersion() + " ~~~ Loading plugins, please wait...");
splashScreen = new VBox();
splashScreen.getChildren().addAll(splash, progressText);
progressText.setAlignment(Pos.CENTER);
}
#Override
public void start(Stage primaryStage) throws Exception {
this.preloaderStage = primaryStage;
Scene splashScene = new Scene(splashScreen);
this.preloaderStage.initStyle(StageStyle.UNDECORATED);
final Rectangle2D bounds = Screen.getPrimary().getBounds();
this.preloaderStage.setScene(splashScene);
this.preloaderStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - WIDTH / 2);
this.preloaderStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - HEIGHT / 2);
this.preloaderStage.show();
}
}
And then in my main class Demo I simply have:
public class Demo extends Application {
#Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new
FXMLLoader(Demo.class.getResource("FXMLDocument.fxml"));
GridPane root = loader.load();
--------other app code here---------
}
public static void main(String[] args) {
LauncherImpl.launchApplication(Demo.class, SplashController.class, args);
}
}
Likely, you are executing some long running process on the JavaFX application thread or a thread involved in the application startup, which prevents the smooth operation of the preloader.
I suggest you review an Oracle Preloader sample and compare to your application. Ensure that you are using concurrent features like Task correctly, similar to the linked example. Check the linked sample works in your environment.
Source code (just copied from the Oracle Preloader sample link)
Note how in the start method of the main LongAppInit application class, that a Task and thread is spawned to ensure that the long application initiation does not take place on the JavaFX application thread. Also see how the notifyPreloader() method of application is called at various times within the long application initialization to let the preloader know of the current state of the initialization process so that it can reflect the progress accurately in the UI in real time.
LongAppInitPreloader.java
public class LongAppInitPreloader extends Preloader {
ProgressBar bar;
Stage stage;
boolean noLoadingProgress = true;
private Scene createPreloaderScene() {
bar = new ProgressBar(0);
BorderPane p = new BorderPane();
p.setCenter(bar);
return new Scene(p, 300, 150);
}
public void start(Stage stage) throws Exception {
this.stage = stage;
stage.setScene(createPreloaderScene());
stage.show();
}
#Override
public void handleProgressNotification(ProgressNotification pn) {
//application loading progress is rescaled to be first 50%
//Even if there is nothing to load 0% and 100% events can be
// delivered
if (pn.getProgress() != 1.0 || !noLoadingProgress) {
bar.setProgress(pn.getProgress()/2);
if (pn.getProgress() > 0) {
noLoadingProgress = false;
}
}
}
#Override
public void handleStateChangeNotification(StateChangeNotification evt) {
//ignore, hide after application signals it is ready
}
#Override
public void handleApplicationNotification(PreloaderNotification pn) {
if (pn instanceof ProgressNotification) {
//expect application to send us progress notifications
//with progress ranging from 0 to 1.0
double v = ((ProgressNotification) pn).getProgress();
if (!noLoadingProgress) {
//if we were receiving loading progress notifications
//then progress is already at 50%.
//Rescale application progress to start from 50%
v = 0.5 + v/2;
}
bar.setProgress(v);
} else if (pn instanceof StateChangeNotification) {
//hide after get any state update from application
stage.hide();
}
}
}
LongAppInit.java
public class LongInitApp extends Application {
Stage stage;
BooleanProperty ready = new SimpleBooleanProperty(false);
private void longStart() {
//simulate long init in background
Task task = new Task<Void>() {
#Override
protected Void call() throws Exception {
int max = 10;
for (int i = 1; i <= max; i++) {
Thread.sleep(200);
// Send progress to preloader
notifyPreloader(new ProgressNotification(((double) i)/max));
}
// After init is ready, the app is ready to be shown
// Do this before hiding the preloader stage to prevent the
// app from exiting prematurely
ready.setValue(Boolean.TRUE);
notifyPreloader(new StateChangeNotification(
StateChangeNotification.Type.BEFORE_START));
return null;
}
};
new Thread(task).start();
}
#Override
public void start(final Stage stage) throws Exception {
// Initiate simulated long startup sequence
longStart();
stage.setScene(new Scene(new Label("Application started"),
400, 400));
// After the app is ready, show the stage
ready.addListener(new ChangeListener<Boolean>(){
public void changed(
ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
if (Boolean.TRUE.equals(t1)) {
Platform.runLater(new Runnable() {
public void run() {
stage.show();
}
});
}
}
});;
}
}

JavaFX 2. How to stop or pause all animations?

I am working on creating a small game.
I use scene switching (scene with a main game's screen and scene with some Help information). So, I decided to use HashMap scenes and set all scenes there. And clicking the button "Help" causes the scene switching.
But I have an issue. I want to stop all animations on non-active scene and currently I just set scene as NULL. I know that it is very bad realization.
Could somebody help me and also explain how to pause or stop all animations on scene?
Setting scene on primaryStage:
public static void setSceneToStage(String sceneId, Stage stage) {
SceneCollection.instance().clearCurrentActiveScene();
SceneCollection.instance().setNewActiveScene(sceneId);
stage.setScene(SceneCollection.instance().getScene(sceneId));
stage.setTitle(sceneId);
}
Clearing non-active scene:
public void clearCurrentActiveScene() {
if(activeScene != null) {
scenes.get(activeScene).clearScene();
}
}
public void clearScene() {
scene = null;
}
Initialize new scene:
public void setNewActiveScene(String sceneId) {
activeScene = sceneId;
scenes.get(sceneId).init();
}
public void init() {
scene = new Scene(new Pane(), 300, 300);
}
I think your program has to have a structure that you can have access to all transitions at time, for example you can have ''TransitonManager Class'' and in that class you have a arraylist of transitions and then you can add this transitions to that in their constructors and then when ever you want , you can have access to all transitions and stop them.
class TransitionManger{
public static ArrayList<Transition> transitions = new ArrayList<>();
}
class CustomTransition extends Transition{
CustomTransition(){
TransitionManger.transitions.add(this);
}
#Override
protected void interpolate(double v) {
//todo do what you want
}
}
you can also use singleton design pattern for TransitionManger for better encapsulation.

Resources