After click myButton runs 2 Thread. First change the button image, second - loop. I want my program at first сhange image and after run loop. But it doesnt work, they are finished in one moment.
myButton.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
ImageView imageView = new ImageView(image);
imageView.setFitHeight(my_button_height - 16);
imageView.setFitWidth(my_button_width - 16);
myButton.setStyle("-fx-background-color: #ffffff00; ");
myButton.setGraphic(imageView);
}
});
thread.run();
try {
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 15; i++){
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
thread1.run();
}
});
}
I tried to add .join. It didnt help
Use a
PauseTransition, not threadsYou don't need to use threads to implement your requirement.
The issue is that there is no pause after a player action under certain conditions, so the player cannot see the cards they have flipped over, before they are flipped back.
This can be fixed using a
PauseTransition. Usage is explained in this answer:Example
Here is some example code for a memory game. The example:
The relevant code is the snippet:
This is just a demo app, it isn't thoroughly tested and may have some bugs in it. The demo is probably more complex then needed, it uses a filtered list to register flipped cards, but could be simplified with just a couple of object properties to represent flipped cards instead.
For a slightly more complex app (or even this one refactored), I'd suggest using a more MVC style approach where the game state is modeled and tested independent of the UI, but for this proof-of-concept demo, the code below is OK for that purpose.
Hopefully, it illustrates one way to use the
PauseTransitionconcept to solve an issue similar to the one you have.MemoryGame.java
Tile.java
MemoryGameApp.java