Reputation: 388
I want somehow to make the button change his position randomly when i push the button. I've got one idea how to solve this problem, one of them i've highlighted below, but i already think that this is not what i need.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Ulesanne6 extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Test");
Button btn = new Button();
btn.setText("Hello");
btn.setOnAction(new EventHandler <javafx.event.ActionEvent>() {
@Override
public void handle(javafx.event.ActionEvent event) {
//btn.setLayoutY(Math.random());
//btn.setLayoutX(Math.random());
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 800, 600));
primaryStage.show();
}
}
I think that somewhere here i suppose to do that, but i don't know how... yet.
public void handle(javafx.event.ActionEvent event) {
//btn.setLayoutY(Math.random());
//btn.setLayoutX(Math.random());
}
Upvotes: 1
Views: 853
Reputation: 12002
How about this?
public void handle(javafx.event.ActionEvent event) {
btn.setTranslateX(ThreadLocalRandom.current().nextDouble(800));
btn.setTranslateY(ThreadLocalRandom.current().nextDouble(600));
}
You might also want to make sure that the button is placed somewhere on the screen and not off the screen. So if you know the width and height of the button, take it into account.
public void handle(javafx.event.ActionEvent event) {
btn.setTranslateX(ThreadLocalRandom.current().nextDouble(800 - buttonWidth));
btn.setTranslateY(ThreadLocalRandom.current().nextDouble(600 - buttonHeight));
}
EDIT: Please note that you are using a StackPane
as your root parent. StackPane
likes to position its children based on alignment attribute of the StackPane
. As such, for my answer to work correctly, you must make your root parent a Group
instead of a StackPane
. A regular Pane
can also work.
Group root = new Group();
Upvotes: 2