JavaFX position dialog and stage in center of screen - javafx

The following codes demonstrates centering of a dialog and the stage in the center of the screen. The dialog is supposed to be displayed first for the user to enter the login credentials. After successful login, the main window (stage) is then displayed. I found the solution of centering the dialog and stage from this web site, but it doesn't seem very ideal. For both the dialog and stage, they have to be displayed first before we can calculate the coordinates and then positioning them in the center. This means that we can see the dialog and the main window moving to the center after they are displayed. Is there a better way? Ideally, they should be positioned in the center before they are displayed.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;
public class Demo extends Application {
private Stage primaryStage;
private Dialog<String> dialog;
private Button createUserButton = new Button("Create User");
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
Text usersLabel = new Text("Current Users:");
TableColumn<User, String> indexColumn = new TableColumn<User, String>("No.");
indexColumn.setMaxWidth(1f * Integer.MAX_VALUE * 10);
indexColumn.setCellValueFactory(p -> p.getValue().indexProperty());
TableColumn<User, String> userNameColumn = new TableColumn<User, String>("User Name");
userNameColumn.setMaxWidth(1f * Integer.MAX_VALUE * 60);
userNameColumn.setCellValueFactory(p -> p.getValue().userNameProperty());
TableColumn<User, String> roleColumn = new TableColumn<User, String>("Role");
roleColumn.setMaxWidth(1f * Integer.MAX_VALUE * 30);
roleColumn.setCellValueFactory(p -> p.getValue().roleProperty());
TableView<User> tableView = new TableView<User>();
tableView.getColumns().add(indexColumn);
tableView.getColumns().add(userNameColumn);
tableView.getColumns().add(roleColumn);
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
Text dummyLabel = new Text("");
VBox leftPane = new VBox(5);
leftPane.getChildren().addAll(usersLabel, tableView);
VBox rightPane = new VBox(20);
rightPane.setFillWidth(true);
rightPane.getChildren().addAll(dummyLabel, createUserButton);
GridPane mainPane = new GridPane();
mainPane.setPadding(new Insets(10, 0, 0, 10));
mainPane.setHgap(20);
mainPane.add(leftPane, 0, 0);
mainPane.add(rightPane, 1, 0);
Scene scene = new Scene(mainPane);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
showDialog();
}
private void showDialog() {
dialog = new Dialog<>();
dialog.setTitle("Login");
dialog.setHeaderText("Please enter User Name and Password to login.");
dialog.setResizable(false);
Label userNameLabel = new Label("User Name:");
Label passwordLabel = new Label("Password:");
TextField userNameField = new TextField();
PasswordField passwordField = new PasswordField();
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 35, 20, 35));
grid.add(userNameLabel, 1, 1);
grid.add(userNameField, 2, 1);
grid.add(passwordLabel, 1, 2);
grid.add(passwordField, 2, 2);
dialog.getDialogPane().setContent(grid);
dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
Button okButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
okButton.addEventFilter(ActionEvent.ACTION, event -> {
createUser(userNameField.getText().trim(), passwordField.getText());
event.consume();
});
dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
Platform.runLater(() -> {
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
Window window = dialog.getDialogPane().getScene().getWindow();
window.setX((screenBounds.getWidth() - window.getWidth()) / 2);
window.setY((screenBounds.getHeight() - window.getHeight()) / 2);
});
dialog.showAndWait();
}
private void createUser(String userName, String password) {
dialog.getDialogPane().setDisable(true);
dialog.getDialogPane().getScene().setCursor(Cursor.WAIT);
Task<Boolean> task = new Task<Boolean>() {
#Override
public Boolean call() {
try {
Thread.sleep(100);
} catch (InterruptedException exception) {
}
return Boolean.TRUE;
}
};
task.setOnSucceeded(e -> {
Boolean success = task.getValue();
dialog.getDialogPane().setDisable(false);
dialog.getDialogPane().getScene().setCursor(Cursor.DEFAULT);
if (success.booleanValue()) {
Platform.runLater(() -> {
dialog.close();
primaryStage.show();
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
primaryStage.setX((screenBounds.getWidth() - primaryStage.getWidth()) / 2);
primaryStage.setY((screenBounds.getHeight() - primaryStage.getHeight()) / 2);
});
} else {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Login Error");
alert.setHeaderText("Unable to login.");
alert.showAndWait();
}
});
new Thread(task).start();
}
public static void main(String[] arguments) {
Application.launch(arguments);
}
}
class User {
private StringProperty index;
private StringProperty userName;
private StringProperty role;
public String getIndex() {
return indexProperty().get();
}
public StringProperty indexProperty() {
if (index == null) {
index = new SimpleStringProperty(this, "index");
}
return index;
}
public void setIndex(String index) {
indexProperty().set(index);
}
public String getUserName() {
return userNameProperty().get();
}
public StringProperty userNameProperty() {
if (userName == null) {
userName = new SimpleStringProperty(this, "userName");
}
return userName;
}
public void setUserName(String userName) {
userNameProperty().set(userName);
}
public String getRole() {
return roleProperty().get();
}
public StringProperty roleProperty() {
if (role == null) {
role = new SimpleStringProperty(this, "role");
}
return role;
}
public void setRole(String role) {
roleProperty().set(role);
}
}
Below is solution by setting custom dimensions to stage and dialog. It works for the stage but it doesn't work for the dialog.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
public class Demo extends Application {
private Stage primaryStage;
private Dialog<String> dialog;
private Button createUserButton = new Button("Create User");
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
Text usersLabel = new Text("Current Users:");
TableColumn<User, String> indexColumn = new TableColumn<User, String>("No.");
indexColumn.setMaxWidth(1f * Integer.MAX_VALUE * 10);
indexColumn.setCellValueFactory(p -> p.getValue().indexProperty());
TableColumn<User, String> userNameColumn = new TableColumn<User, String>("User Name");
userNameColumn.setMaxWidth(1f * Integer.MAX_VALUE * 60);
userNameColumn.setCellValueFactory(p -> p.getValue().userNameProperty());
TableColumn<User, String> roleColumn = new TableColumn<User, String>("Role");
roleColumn.setMaxWidth(1f * Integer.MAX_VALUE * 30);
roleColumn.setCellValueFactory(p -> p.getValue().roleProperty());
TableView<User> tableView = new TableView<User>();
tableView.getColumns().add(indexColumn);
tableView.getColumns().add(userNameColumn);
tableView.getColumns().add(roleColumn);
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
Text dummyLabel = new Text("");
VBox leftPane = new VBox(5);
leftPane.getChildren().addAll(usersLabel, tableView);
VBox rightPane = new VBox(20);
rightPane.setFillWidth(true);
rightPane.getChildren().addAll(dummyLabel, createUserButton);
GridPane mainPane = new GridPane();
mainPane.setPadding(new Insets(10, 0, 0, 10));
mainPane.setHgap(20);
mainPane.add(leftPane, 0, 0);
mainPane.add(rightPane, 1, 0);
float width = 372f;
float height = 470f;
Scene scene = new Scene(mainPane, width, height);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
primaryStage.setX((screenBounds.getWidth() - width) / 2);
primaryStage.setY((screenBounds.getHeight() - height) / 2);
showDialog();
}
private void showDialog() {
dialog = new Dialog<>();
dialog.setTitle("Login");
dialog.setHeaderText("Please enter User Name and Password to login.");
dialog.setResizable(false);
Label userNameLabel = new Label("User Name:");
Label passwordLabel = new Label("Password:");
TextField userNameField = new TextField();
PasswordField passwordField = new PasswordField();
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 35, 20, 35));
grid.add(userNameLabel, 1, 1);
grid.add(userNameField, 2, 1);
grid.add(passwordLabel, 1, 2);
grid.add(passwordField, 2, 2);
dialog.getDialogPane().setContent(grid);
dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
Button okButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
okButton.addEventFilter(ActionEvent.ACTION, event -> {
login(userNameField.getText().trim(), passwordField.getText());
event.consume();
});
dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
float width = 509f;
float height = 168f;
dialog.setWidth(width);
dialog.setHeight(height);
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
dialog.setX((screenBounds.getWidth() - width) / 2);
dialog.setY((screenBounds.getHeight() - height) / 2);
dialog.showAndWait();
}
private void login(String userName, String password) {
dialog.getDialogPane().setDisable(true);
dialog.getDialogPane().getScene().setCursor(Cursor.WAIT);
Task<Boolean> task = new Task<Boolean>() {
#Override
public Boolean call() {
try {
Thread.sleep(100);
} catch (InterruptedException exception) {
}
return Boolean.TRUE;
}
};
task.setOnSucceeded(e -> {
Boolean success = task.getValue();
dialog.getDialogPane().setDisable(false);
dialog.getDialogPane().getScene().setCursor(Cursor.DEFAULT);
if (success.booleanValue()) {
Platform.runLater(() -> {
primaryStage.show();
});
} else {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Login Error");
alert.setHeaderText("Unable to login.");
alert.showAndWait();
}
});
new Thread(task).start();
}
public static void main(String[] arguments) {
Application.launch(arguments);
}
}
class User {
private StringProperty index;
private StringProperty userName;
private StringProperty role;
public String getIndex() {
return indexProperty().get();
}
public StringProperty indexProperty() {
if (index == null) {
index = new SimpleStringProperty(this, "index");
}
return index;
}
public void setIndex(String index) {
indexProperty().set(index);
}
public String getUserName() {
return userNameProperty().get();
}
public StringProperty userNameProperty() {
if (userName == null) {
userName = new SimpleStringProperty(this, "userName");
}
return userName;
}
public void setUserName(String userName) {
userNameProperty().set(userName);
}
public String getRole() {
return roleProperty().get();
}
public StringProperty roleProperty() {
if (role == null) {
role = new SimpleStringProperty(this, "role");
}
return role;
}
public void setRole(String role) {
roleProperty().set(role);
}
}
JKostikiadis's solution:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class TestApp extends Application {
private static final double WIDTH = 316.0;
private static final double HEIGHT = 339.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
HBox pane = new HBox();
pane.setAlignment(Pos.CENTER);
Button b = new Button("click me");
b.setOnAction(e -> {
showDialog();
});
pane.getChildren().add(b);
Scene scene = new Scene(pane, 300, 300);
stage.setScene(scene);
centerStage(stage, WIDTH, HEIGHT);
stage.show();
}
private void showDialog() {
Alert dialog = new Alert(AlertType.ERROR);
dialog.setTitle("Error Dialog");
dialog.setHeaderText("Look, an Error Dialog");
dialog.setContentText("Ooops, there was an error!\nOoops, there was an error!");
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
centerStage(stage, -10000, -10000);
dialog.show();
System.out.println(stage.getWidth() + " " + stage.getHeight());
dialog.hide();
centerStage(stage, stage.getWidth(), stage.getHeight());
dialog.showAndWait();
}
private void centerStage(Stage stage, double width, double height) {
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
stage.setX((screenBounds.getWidth() - width) / 2);
stage.setY((screenBounds.getHeight() - height) / 2);
}
}

Unfortunately, you have to wait for the width/height of the Window (or Dialog) to be computed as well as for the Window to be shown. Since the Window is visible you will always notice the window moving when updating the xy-position.
Doing the update when the WindowEvent.WINDOW_SHOWN event is fired might provide a better result:
final Window window = dialog.getDialogPane().getScene().getWindow();
window.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
window.setX((screenBounds.getWidth() - window.getWidth()) / 2);
window.setY((screenBounds.getHeight() - window.getHeight()) / 2);
}
});
And for the primaryStage
primaryStage.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
primaryStage.setX((screenBounds.getWidth() - primaryStage.getWidth()) / 2);
primaryStage.setY((screenBounds.getHeight() - primaryStage.getHeight()) / 2);
}
});
primaryStage.show();
But as mentioned by JKostikiadis, a better and proper solution might be to compute your own dimension with respect to the current screen size.
Here is the small improvement I can see.
When running your demo on my machine, the movement is erratic:
I can see a small improvement when using WindowEvent.WINDOW_SHOWN (without usingPlatform.runLater for the first Dialog):
Anyway, I don't think using Platform.runLater for displaying the first window is ideal as there is no guarantee that showAndWait() will always be executed before the Runnable

You can center a stage on another stage before rendering it by applying the css which will provide you with the width/height.
For example.
From where you create the stage:
WindowHelper.centerChildWindowOnStage(stage, primaryStage); //assuming primary is the stage you want to center on
stage.show();
below is the code to center the unshown window (assume this is on a WindowHelper class to be reused in the app).
public static void centerChildWindowOnStage(Stage stage, Stage primaryStage ) {
if(primaryStage == null){
return;
}
double x = stage.getX();
double y = stage.getY();
// Firstly we need to force CSS and layout to happen, as the dialogPane
// may not have been shown yet (so it has no dimensions)
stage.getScene().getRoot().applyCss();
stage.getScene().getRoot().layout();
final Scene ownerScene = primaryStage.getScene();
final double titleBarHeight = ownerScene.getY();
// because Stage does not seem to centre itself over its owner, we
// do it here.
// then we can get the dimensions and position the dialog appropriately.
final double dialogWidth = stage.getScene().getRoot().prefWidth(-1);
final double dialogHeight = stage.getScene().getRoot().prefHeight(dialogWidth);
final double ownerWidth = primaryStage.getScene().getRoot().prefWidth(-1);
final double ownerHeight = primaryStage.getScene().getRoot().prefHeight(ownerWidth);
if(dialogWidth < ownerWidth){
x = primaryStage.getX() + (ownerScene.getWidth() / 2.0) - (dialogWidth / 2.0);
}else {
x = primaryStage.getX();
stage.setWidth(dialogWidth);
}
if(dialogHeight < ownerHeight){
y = primaryStage.getY() + titleBarHeight / 2.0 + (ownerScene.getHeight() / 2.0) - (dialogHeight / 2.0);
}else {
y = primaryStage.getY();
}
stage.setX(x);
stage.setY(y);
}

Well because you ask me in the commends I am going to provide an example of setting the Stage ( main application or dialog ) to the center of the screen by early initialization of their dimensions.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class TestApp extends Application {
private static final double WIDTH = 316.0;
private static final double HEIGHT = 339.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
HBox pane = new HBox();
pane.setAlignment(Pos.CENTER);
Button b = new Button("click me");
b.setOnAction(e -> {
showDialog();
});
pane.getChildren().add(b);
Scene scene = new Scene(pane, 300, 300);
stage.setScene(scene);
centerStage(stage, WIDTH, HEIGHT);
stage.show();
System.out.println(stage.getWidth() + " " + stage.getHeight());
}
private void showDialog() {
Alert dialog = new Alert(AlertType.ERROR);
dialog.setTitle("Error Dialog");
dialog.setHeaderText("Look, an Error Dialog");
dialog.setContentText("Ooops, there was an error!");
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
centerStage(stage, 366, 175);
dialog.showAndWait();
}
private void centerStage(Stage stage, double width, double height) {
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
stage.setX((screenBounds.getWidth() - width) / 2);
stage.setY((screenBounds.getHeight() - height) / 2);
}
}
In the example above you will see that I have specify the application dimensions to 300,300 but I am using for width = 316.0 and height = 339.0 and you might wondering why. It's because the stage size will always be a little bigger than the Scene ( borders + Title bar etc ) so in order to find the real width and height of the Stage you will have to print the dimensions of the stage after you show it. The same logic is happening to the Dialog.
Important : Of course you could forget all about the above and just do :
stage.setWidth(300); // or a variable here
stage.setHeight(300);
But this will affect your internal components cause if previously the scene's components had a size of 300,300 now they are going to be squeezed to something less in order to make the stage to fix the size of 300,300 so in that case yes it might affect the way your application looks like.
In the past I was searching for a way to find the dimension of a label before I show it. I found out that it was possible to get it's dimensions by adding it to the Scene and then call
labe.impl_processCSS(true);
System.out.println(labe.prefWidth(-1) + "/" + labe.prefHeight(-1));
Now If I try to do the same for the main pane in the above application it shows 59/25 which are the dimensions of the button itself so this approach is not going to work in case of someone wondering about it.
Edit :
I don't really want to show this "hack" cause I find it stupid and i am sure there is a better way, but until I find it here you go :
private void showDialog() {
Alert dialog = new Alert(AlertType.ERROR);
dialog.setTitle("Error Dialog");
dialog.setHeaderText("Look, an Error Dialog");
dialog.setContentText("Ooops, there was an error!\nOoops, there was an error!");
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
centerStage(stage, -10000, -10000);
dialog.show();
centerStage(stage, stage.getWidth(), stage.getHeight());
}

Related

JavaFX Pan and Zoom with Draggable Nodes Inside

I have a simple JavaFX pan and zoom application as show below. The pan and zoom functionality work great, but I would also like to be able to drag and drop the circle node too. The problem I have is that the scrollpane gets all of the mouse events first, so I'm unable to assign a drag and drop to just the circle. Is it possible to have a draggable/zoomable scrollpane and also be able to drag a node inside the pane?
Screenshot
Here us the code that I'm using:
package sample;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
private ScrollPane scrollPane = new ScrollPane();
private final DoubleProperty zoomProperty = new SimpleDoubleProperty(1.0d);
private final DoubleProperty deltaY = new SimpleDoubleProperty(0.0d);
private final Group group = new Group();
ImageView bigImageView = null;
PanAndZoomPane panAndZoomPane = null;
Pane featuresPane = new Pane();
#Override
public void start(Stage primaryStage) throws Exception{
bigImageView = new ImageView();
StackPane bigStackpane = new StackPane();
bigStackpane.getChildren().add(bigImageView);
bigStackpane.getChildren().add(featuresPane);
featuresPane.toFront();
featuresPane.setOpacity(.8);
Circle circle = new Circle();
circle.setCenterX(200);
circle.setCenterY(200);
circle.setRadius(100);
circle.setFill(Color.RED);
circle.setOnMouseClicked(e -> {
System.out.println("circle clicked");
});
featuresPane.getChildren().add(circle);
scrollPane.setPannable(true);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
group.getChildren().add(bigImageView);
group.getChildren().add(bigStackpane);
panAndZoomPane = new PanAndZoomPane();
zoomProperty.bind(panAndZoomPane.myScale);
deltaY.bind(panAndZoomPane.deltaY);
panAndZoomPane.getChildren().add(group);
SceneGestures sceneGestures = new SceneGestures(panAndZoomPane);
scrollPane.setContent(panAndZoomPane);
panAndZoomPane.toBack();
scrollPane.addEventFilter( MouseEvent.MOUSE_CLICKED, sceneGestures.getOnMouseClickedEventHandler());
scrollPane.addEventFilter( MouseEvent.MOUSE_PRESSED, sceneGestures.getOnMousePressedEventHandler());
scrollPane.addEventFilter( MouseEvent.MOUSE_DRAGGED, sceneGestures.getOnMouseDraggedEventHandler());
scrollPane.addEventFilter( ScrollEvent.ANY, sceneGestures.getOnScrollEventHandler());
AnchorPane bigImageAnchorPane = new AnchorPane();
bigImageAnchorPane.getChildren().add(scrollPane);
Image image = new Image("https://i.imgur.com/8p1XBag.jpg");
bigImageView.setImage(image);
bigImageAnchorPane.setTopAnchor(scrollPane, 1.0d);
bigImageAnchorPane.setRightAnchor(scrollPane, 1.0d);
bigImageAnchorPane.setBottomAnchor(scrollPane, 1.0d);
bigImageAnchorPane.setLeftAnchor(scrollPane, 1.0d);
BorderPane root = new BorderPane(bigImageAnchorPane);
Label label = new Label("Pan and Zoom Test");
root.setTop(label);
Scene scene = new Scene(root, 1000, 1000);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
class PanAndZoomPane extends Pane {
public static final double DEFAULT_DELTA = 1.5d; //1.3d
DoubleProperty myScale = new SimpleDoubleProperty(1.0);
public DoubleProperty deltaY = new SimpleDoubleProperty(0.0);
private Timeline timeline;
public PanAndZoomPane() {
this.timeline = new Timeline(30);//60
// add scale transform
scaleXProperty().bind(myScale);
scaleYProperty().bind(myScale);
}
public double getScale() {
return myScale.get();
}
public void setScale( double scale) {
myScale.set(scale);
}
public void setPivot( double x, double y, double scale) {
// note: pivot value must be untransformed, i. e. without scaling
// timeline that scales and moves the node
timeline.getKeyFrames().clear();
timeline.getKeyFrames().addAll(
new KeyFrame(Duration.millis(100), new KeyValue(translateXProperty(), getTranslateX() - x)), //200
new KeyFrame(Duration.millis(100), new KeyValue(translateYProperty(), getTranslateY() - y)), //200
new KeyFrame(Duration.millis(100), new KeyValue(myScale, scale)) //200
);
timeline.play();
}
public double getDeltaY() {
return deltaY.get();
}
public void setDeltaY( double dY) {
deltaY.set(dY);
}
}
/**
* Mouse drag context used for scene and nodes.
*/
class DragContext {
double mouseAnchorX;
double mouseAnchorY;
double translateAnchorX;
double translateAnchorY;
}
/**
* Listeners for making the scene's canvas draggable and zoomable
*/
public class SceneGestures {
private DragContext sceneDragContext = new DragContext();
PanAndZoomPane panAndZoomPane;
public SceneGestures( PanAndZoomPane canvas) {
this.panAndZoomPane = canvas;
}
public EventHandler<MouseEvent> getOnMouseClickedEventHandler() {
return onMouseClickedEventHandler;
}
public EventHandler<MouseEvent> getOnMousePressedEventHandler() {
return onMousePressedEventHandler;
}
public EventHandler<MouseEvent> getOnMouseDraggedEventHandler() {
return onMouseDraggedEventHandler;
}
public EventHandler<ScrollEvent> getOnScrollEventHandler() {
return onScrollEventHandler;
}
private EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
sceneDragContext.mouseAnchorX = event.getX();
sceneDragContext.mouseAnchorY = event.getY();
sceneDragContext.translateAnchorX = panAndZoomPane.getTranslateX();
sceneDragContext.translateAnchorY = panAndZoomPane.getTranslateY();
}
};
private EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
panAndZoomPane.setTranslateX(sceneDragContext.translateAnchorX + event.getX() - sceneDragContext.mouseAnchorX);
panAndZoomPane.setTranslateY(sceneDragContext.translateAnchorY + event.getY() - sceneDragContext.mouseAnchorY);
event.consume();
}
};
/**
* Mouse wheel handler: zoom to pivot point
*/
private EventHandler<ScrollEvent> onScrollEventHandler = new EventHandler<ScrollEvent>() {
#Override
public void handle(ScrollEvent event) {
double delta = PanAndZoomPane.DEFAULT_DELTA;
double scale = panAndZoomPane.getScale(); // currently we only use Y, same value is used for X
double oldScale = scale;
panAndZoomPane.setDeltaY(event.getDeltaY());
if (panAndZoomPane.deltaY.get() < 0) {
scale /= delta;
} else {
scale *= delta;
}
double f = (scale / oldScale)-1;
double dx = (event.getX() - (panAndZoomPane.getBoundsInParent().getWidth()/2 + panAndZoomPane.getBoundsInParent().getMinX()));
double dy = (event.getY() - (panAndZoomPane.getBoundsInParent().getHeight()/2 + panAndZoomPane.getBoundsInParent().getMinY()));
panAndZoomPane.setPivot(f*dx, f*dy, scale);
event.consume();
}
};
/**
* Mouse click handler
*/
private EventHandler<MouseEvent> onMouseClickedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.PRIMARY)) {
if (event.getClickCount() == 2) {
System.out.println("Image Layer Double Clicked...");
}else{
System.out.println("Image Layer Clicked...");
}
}
}
};
}
}
Your code is adding behavior via event filters. These filters are invoked during the event capturing phase which means they are invoked before the events reach your circle. You should strive to implement your behavior via event handlers, which are invoked during the event bubbling phase. Then you can consume events to prevent them from reaching ancestors, allowing you to drag your circle without scrolling/panning the scroll-pane content. For more information about event handling and propagation, check out this tutorial.
Here's a proof-of-concept which adds the zoom-handling to the scroll-pane's content and still let's you drag around a circle:
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
// using your example image
ImageView imageView = new ImageView("https://i.imgur.com/8p1XBag.jpg");
Circle circle = new Circle(100, 100, 25, Color.FIREBRICK);
circle.setOnMousePressed(
e -> {
// prevent pannable ScrollPane from changing cursor on drag-detected (implementation
// detail)
e.setDragDetect(false);
Point2D offset =
new Point2D(e.getX() - circle.getCenterX(), e.getY() - circle.getCenterY());
circle.setUserData(offset);
e.consume(); // prevents MouseEvent from reaching ScrollPane
});
circle.setOnMouseDragged(
e -> {
// prevent pannable ScrollPane from changing cursor on drag-detected (implementation
// detail)
e.setDragDetect(false);
Point2D offset = (Point2D) circle.getUserData();
circle.setCenterX(e.getX() - offset.getX());
circle.setCenterY(e.getY() - offset.getY());
e.consume(); // prevents MouseEvent from reaching ScrollPane
});
// the zoom-able content of the ScrollPane
Group group = new Group(imageView, circle);
// wrap Group in another Group since it's the former that's scaled and
// Groups only take transformations of their **children** into account (not themselves)
StackPane content = new StackPane(new Group(group));
content.setMinSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
// due to later configuration, the StackPane will always cover the entire viewport
content.setOnScroll(
e -> {
if (e.isShortcutDown() && e.getDeltaY() != 0) {
if (e.getDeltaY() < 0) {
group.setScaleX(Math.max(group.getScaleX() - 0.1, 0.5));
} else {
group.setScaleX(Math.min(group.getScaleX() + 0.1, 5.0));
}
group.setScaleY(group.getScaleX());
e.consume(); // prevents ScrollEvent from reaching ScrollPane
}
});
// use StackPane (or some other resizable node) as content since Group is not
// resizable. Note StackPane will center content if smaller than viewport.
ScrollPane scrollPane = new ScrollPane(content);
scrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setPannable(true);
// ensure StackPane content always has at least the same dimensions as the viewport
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
primaryStage.setScene(new Scene(scrollPane, 1000, 650));
primaryStage.show();
}
}
Note this does not exactly replicate the behavior of your example. It does not use animations nor does it zoom on a pivot point. But hopefully it can help you move forward in your application.

High refreshing rate in JavaFX

I'm trying to write a program with an equalizer, a frequency analyzer and a sound level meter. The model part seems to work very well but I'm experimenting some bugs with the IHM.
My last bug is with the level meter. After a while (from few milliseconds to few seconds), it freezes and don't update anymore. So, here is a (simplified) version of it. I added the runnable part to test and reproduce the bug. Of course, this bug appears sooner when I add other graphical components which also need to refresh very frequently. For example, the frequency analyze is represented by a line-chart with something like 1000 points.
public class LevelMeter2 extends Parent implements Runnable {
private IntegerProperty levelMeterHeight = new SimpleIntegerProperty();
private Rectangle led;
private IntegerProperty height = new SimpleIntegerProperty();
private IntegerProperty width = new SimpleIntegerProperty();
private DoubleProperty linearValue = new SimpleDoubleProperty();
private Color backgroundColor=Color.BLACK;
private double minLinearValue, maxLinearValue;
public LevelMeter2 (int height2, int width2) {
this.height.set(height2);
this.levelMeterHeight.bind(height.multiply(0.9));
this.width.set(width2);
linearValue.set(1.0);
minLinearValue = Math.pow(10, -60.0/100);
maxLinearValue = Math.pow(10, 3.0/100)-minLinearValue;
Rectangle levelMeterShape = new Rectangle();
levelMeterShape.widthProperty().bind(width);
levelMeterShape.heightProperty().bind(height);
levelMeterShape.setStroke(backgroundColor);
this.getChildren().add(levelMeterShape);
led = new Rectangle();
led.widthProperty().bind(width.multiply(0.8));
led.translateXProperty().bind(width.multiply(0.1));
led.heightProperty().bind(levelMeterHeight.multiply(linearValue));
led.setFill(Color.AQUA);
Rotate rotate = new Rotate();
rotate.pivotXProperty().bind(width.multiply(0.8).divide(2));
rotate.pivotYProperty().bind(height.divide(2));
rotate.setAngle(180);
led.getTransforms().add(rotate);
this.getChildren().add(led);
}
public double convertdBToLinearValue (double dB) {
return ((double)Math.round(100 * ((Math.pow(10, dB/100)-minLinearValue)/maxLinearValue)) ) /100 ;
//return (Math.pow(10, dB/100)-minLinearValue)/maxLinearValue;
}
public double convertLinearValueTodB (double linearValue) {
return 100*Math.log10(linearValue*maxLinearValue+minLinearValue);
}
public void setValue (double dB) {
if (dB>3) {
dB=3;
}
linearValue.setValue(convertdBToLinearValue(dB));
}
#Override
public void run() {
int i = 0;
double value=-20;
while (i<1000) {
setValue(value);
value = (Math.random()-0.5)*10+value;
if (value>3) {
value=3;
}
if (value<-60) {
value=-60;
}
i++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("END OF WHILE");
}
}
And a "Main" to test it :
public class MainGraph extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
HBox pane = new HBox();
LevelMeter2 levelMeter = new LevelMeter2(300,30);
Thread t = new Thread(levelMeter);
pane.getChildren().add(levelMeter);
t.start();
Scene scene = new Scene(pane, 300, 300);
primaryStage.setScene(scene);
primaryStage.setTitle("Test IHM");
primaryStage.setOnCloseRequest( event -> {
System.out.println("FIN");
System.exit(0);
});
primaryStage.show();
}
}
What's wrong with my code ? How can I write a more robust code that will allow me high refresh rates of my IHM ? Or how can I prevent from freezing ?
Thank you for you help.
I would suggest you move away from Threads and use something from JavaFX Animation package. In this example Timeline is used. This code is set to run at a rate of about 60 fps. You can adjust that using Duration.millis().
Main
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication342 extends Application
{
#Override
public void start(Stage primaryStage)
{
LevelMeter2 levelMeter = new LevelMeter2(300, 30);
Button button = new Button("Start");
button.setOnAction((event) -> {
switch (button.getText()) {
case "Start":
levelMeter.startAnimation();
button.setText("Stop");
break;
case "Stop":
levelMeter.stopAnimation();
button.setText("Start");
break;
}
});
HBox pane = new HBox(levelMeter, button);
Scene scene = new Scene(pane, 300, 300);
primaryStage.setScene(scene);
primaryStage.setTitle("Test IHM");
primaryStage.setOnCloseRequest(event -> {
System.out.println("FIN");
System.exit(0);
});
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
LevelMeter2
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Parent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.util.Duration;
public final class LevelMeter2 extends Parent
{
private final IntegerProperty levelMeterHeight = new SimpleIntegerProperty();
Timeline timeline;
double value = -20;
private final Rectangle led;
private final IntegerProperty height = new SimpleIntegerProperty();
private final IntegerProperty width = new SimpleIntegerProperty();
private final DoubleProperty linearValue = new SimpleDoubleProperty();
private final Color backgroundColor = Color.BLACK;
private final double minLinearValue;
private final double maxLinearValue;
public LevelMeter2(int height2, int width2)
{
this.height.set(height2);
this.levelMeterHeight.bind(height.multiply(0.9));
this.width.set(width2);
linearValue.set(1.0);
minLinearValue = Math.pow(10, -60.0 / 100);
maxLinearValue = Math.pow(10, 3.0 / 100) - minLinearValue;
Rectangle levelMeterShape = new Rectangle();
levelMeterShape.widthProperty().bind(width);
levelMeterShape.heightProperty().bind(height);
levelMeterShape.setStroke(backgroundColor);
this.getChildren().add(levelMeterShape);
led = new Rectangle();
led.widthProperty().bind(width.multiply(0.8));
led.translateXProperty().bind(width.multiply(0.1));
led.heightProperty().bind(levelMeterHeight.multiply(linearValue));
led.setFill(Color.AQUA);
Rotate rotate = new Rotate();
rotate.pivotXProperty().bind(width.multiply(0.8).divide(2));
rotate.pivotYProperty().bind(height.divide(2));
rotate.setAngle(180);
led.getTransforms().add(rotate);
getChildren().add(led);
timeline = new Timeline(new KeyFrame(Duration.millis(16), (event) -> {
setValue(value);
value = (Math.random() - 0.5) * 10 + value;
if (value > 3) {
value = 3;
}
if (value < -60) {
value = -60;
}
}));
timeline.setCycleCount(Timeline.INDEFINITE);
}
public double convertdBToLinearValue(double dB)
{
return ((double) Math.round(100 * ((Math.pow(10, dB / 100) - minLinearValue) / maxLinearValue))) / 100;
}
public double convertLinearValueTodB(double linearValue)
{
return 100 * Math.log10(linearValue * maxLinearValue + minLinearValue);
}
public void setValue(double dB)
{
if (dB > 3) {
dB = 3;
}
linearValue.setValue(convertdBToLinearValue(dB));
}
public void startAnimation()
{
timeline.play();
}
public void stopAnimation()
{
timeline.stop();
}
}
Multiple LevelMeters Example:
Main
import java.util.ArrayList;
import java.util.List;
import javafx.animation.ParallelTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication342 extends Application
{
#Override
public void start(Stage primaryStage)
{
List<LevelMeter2> levelMeter2s = new ArrayList();
List<Timeline> metersTimelines = new ArrayList();
for (int i = 0; i < 9; i++) {
LevelMeter2 levelMeter2 = new LevelMeter2(300, 30);
levelMeter2s.add(levelMeter2);
metersTimelines.add(levelMeter2.getTimeline());
}
ParallelTransition parallelTransition = new ParallelTransition();
parallelTransition.getChildren().addAll(metersTimelines);
Button button = new Button("Start");
button.setOnAction((event) -> {
switch (button.getText()) {
case "Start":
parallelTransition.play();
button.setText("Stop");
break;
case "Stop":
parallelTransition.stop();
button.setText("Start");
break;
}
});
HBox hBox = new HBox();
hBox.getChildren().addAll(levelMeter2s);
VBox vBox = new VBox(hBox, new StackPane(button));
Scene scene = new Scene(vBox, 300, 350);
primaryStage.setScene(scene);
primaryStage.setTitle("Test IHM");
primaryStage.setOnCloseRequest(event -> {
System.out.println("FIN");
System.exit(0);
});
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
LevelMeter2
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Parent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.util.Duration;
public final class LevelMeter2 extends Parent
{
private final IntegerProperty levelMeterHeight = new SimpleIntegerProperty();
Timeline timeline;
double value = -20;
private final Rectangle led;
private final IntegerProperty height = new SimpleIntegerProperty();
private final IntegerProperty width = new SimpleIntegerProperty();
private final DoubleProperty linearValue = new SimpleDoubleProperty();
private final Color backgroundColor = Color.BLACK;
private final double minLinearValue;
private final double maxLinearValue;
public LevelMeter2(int height2, int width2)
{
this.height.set(height2);
this.levelMeterHeight.bind(height.multiply(0.9));
this.width.set(width2);
linearValue.set(1.0);
minLinearValue = Math.pow(10, -60.0 / 100);
maxLinearValue = Math.pow(10, 3.0 / 100) - minLinearValue;
Rectangle levelMeterShape = new Rectangle();
levelMeterShape.widthProperty().bind(width);
levelMeterShape.heightProperty().bind(height);
levelMeterShape.setStroke(backgroundColor);
this.getChildren().add(levelMeterShape);
led = new Rectangle();
led.widthProperty().bind(width.multiply(0.8));
led.translateXProperty().bind(width.multiply(0.1));
led.heightProperty().bind(levelMeterHeight.multiply(linearValue));
led.setFill(Color.AQUA);
Rotate rotate = new Rotate();
rotate.pivotXProperty().bind(width.multiply(0.8).divide(2));
rotate.pivotYProperty().bind(height.divide(2));
rotate.setAngle(180);
led.getTransforms().add(rotate);
getChildren().add(led);
timeline = new Timeline(new KeyFrame(Duration.millis(25), (event) -> {
setValue(value);
value = (Math.random() - 0.5) * 10 + value;
if (value > 3) {
value = 3;
}
if (value < -60) {
value = -60;
}
}));
timeline.setCycleCount(Timeline.INDEFINITE);
}
public double convertdBToLinearValue(double dB)
{
return ((double) Math.round(100 * ((Math.pow(10, dB / 100) - minLinearValue) / maxLinearValue))) / 100;
}
public double convertLinearValueTodB(double linearValue)
{
return 100 * Math.log10(linearValue * maxLinearValue + minLinearValue);
}
public void setValue(double dB)
{
if (dB > 3) {
dB = 3;
}
linearValue.setValue(convertdBToLinearValue(dB));
}
public void startAnimation()
{
timeline.play();
}
public void stopAnimation()
{
timeline.stop();
}
public Timeline getTimeline()
{
return timeline;
}
}
Your implementation of run() appears to be updating the scene graph from a background thread. As discussed in Concurrency in JavaFX:
The JavaFX scene graph…is not thread-safe and can only be accessed and modified from the UI thread also known as the JavaFX Application thread. Implementing long-running tasks on the JavaFX Application thread inevitably makes an application UI unresponsive."
Instead, use a Task, illustrated here and here. Your implementation of call() can collect data asynchronously and notify the GUI of the current state via updateValue(). Your valueProperty() listener can then invoke setValue() safely. Because "Updates are coalesced to prevent saturation of the FX event queue," your application will perform satisfactorily even on older hardware.
Alternatively, if your audio source is one of the supported Media types, AudioBarChartApp, also seen here, updates the data model of a BarChart in an AudioSpectrumListener registered with the corresponding MediaPlayer. The image below displays pink noise.
private XYChart.Data<String, Number>[] series1Data;
…
audioSpectrumListener = (double timestamp, double duration,
float[] magnitudes, float[] phases) -> {
for (int i = 0; i < series1Data.length; i++) {
series1Data[i].setYValue(magnitudes[i] + 60);
}
};

How can I de-select/ Unfocus everything when presing ESC

I have the following mini-app:
public class TestApp extends Application {
public static void main(final String[] args) {
launch(args);
}
private final AtomicLong counter = new AtomicLong();
#Override
public void start(final Stage primaryStage) {
final VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
final TableView<String> tableView = new TableView<>();
final TableColumn<String, String> column = new TableColumn<>("Text");
column.setCellValueFactory(f -> new SimpleStringProperty(f.getValue()));
tableView.getColumns().add(column);
// Add some sample items to our TableView
for (int i = 0; i < 100; i++) {
tableView.getItems().add("Item #" + counter.incrementAndGet());
}
final Button button = new Button("Add items");
final TextArea t1 = new TextArea();
button.setOnAction(e -> {
final long oldElement = counter.get();
// Add more elements
for (int i = 0; i < 10; i++) {
tableView.getItems().add("Item #" + counter.incrementAndGet());
}
tableView.scrollTo("Item #" + oldElement);
});
root.getChildren().add(button);
root.getChildren().add(t1);
root.getChildren().add(tableView);
// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
When it starts up, the button has focus. If I click in the TextArea, it gets focus.
There is no way now to "unfocus" the TextArea again, besides pressing the button (which will trigger an action, which is unwanted if I only want to get rid of the focus).
How can I release all focus and deselect everything, for example when I pres ESC?
I don't know if this fully meets your requirements, but you can create a boolean variable to keep up with the state of ESCAPE. You can also use a ChangeListener that allows the root node to regain focus anytime it loses it.
import java.util.concurrent.atomic.AtomicLong;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestApp extends Application
{
boolean escActive = false;
final VBox root = new VBox(5);
ChangeListener<Boolean> changeListener1 = new ChangeListener()
{
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue)
{
System.out.println(newValue);
root.requestFocus();
}
};
public static void main(final String[] args)
{
launch(args);
}
private final AtomicLong counter = new AtomicLong();
#Override
public void start(final Stage primaryStage)
{
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
final TableView<String> tableView = new TableView<>();
final TableColumn<String, String> column = new TableColumn<>("Text");
column.setCellValueFactory(f -> new SimpleStringProperty(f.getValue()));
tableView.getColumns().add(column);
// Add some sample items to our TableView
for (int i = 0; i < 100; i++) {
tableView.getItems().add("Item #" + counter.incrementAndGet());
}
final Button button = new Button("Add items");
final TextArea t1 = new TextArea();
button.setOnAction(e -> {
if (!escActive) {
final long oldElement = counter.get();
// Add more elements
for (int i = 0; i < 10; i++) {
tableView.getItems().add("Item #" + counter.incrementAndGet());
}
tableView.scrollTo("Item #" + oldElement);
}
});
root.getChildren().add(button);
root.getChildren().add(t1);
root.getChildren().add(tableView);
root.setOnKeyReleased((event) -> {
System.out.println(event.getCode());
if (event.getCode() == KeyCode.ESCAPE) {
escActive = !escActive;
if (escActive) {
root.requestFocus();
root.focusedProperty().addListener(changeListener1);
}
else {
root.focusedProperty().removeListener(changeListener1);
}
}
});
// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}

Q: Confused about switching screens JavaFX

I dont understand how to switch between the current screen and the register screen:
package Computing;
import javafx.scene.layout.*;import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.Window;
public class Computing extends Application {
Stage stage;
#Override
public void start(Stage primaryStage) throws Exception {
stage = primaryStage;
primaryStage.setTitle("Computing Quiz");
GridPane gridPane = createComputingQuizPane();
// ui controls to gridpane
addUIControls(gridPane);
// scene
Scene scene = new Scene(gridPane, 800, 500);
// primary stage scene set
primaryStage.setScene(scene);
primaryStage.show();
}
private GridPane createComputingQuizPane() {
// Instantiate a new Grid Pane
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setPadding(new Insets(40, 40, 40, 40));
gridPane.setHgap(10);
gridPane.setVgap(10);
return gridPane;
}
private void addUIControls(GridPane gridPane) {
// HEADER
Label headerLabel = new Label("Welcome to the Computing Quiz!");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 24));
gridPane.add(headerLabel, 0,0,2,1);
GridPane.setHalignment(headerLabel, HPos.CENTER);
GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));
// LOGIN BUTTON
Button loginButton = new Button("Login");
loginButton.setPrefHeight(50);
loginButton.setDefaultButton(true);
loginButton.setPrefWidth(125);
gridPane.add(loginButton, 0, 4, 2, 1);
GridPane.setHalignment(loginButton, HPos.CENTER);
GridPane.setMargin(loginButton, new Insets(20, 0,20,0));
// REGISTER BUTTON
Button registerButton = new Button ("Register");
registerButton.setOnAction(e-> buttonClick());
registerButton.setPrefHeight(50);
registerButton.setDefaultButton(true);
registerButton.setPrefWidth(125);
gridPane.add(registerButton,0,5,2,1);
GridPane.setHalignment(registerButton,HPos.CENTER);
GridPane.setMargin(registerButton, new Insets(20,0,20,0));
//registerButton.setOnAction(new EventHandler<ActionEvent>() {
//#Override
//public void handle(ActionEvent event) {
//Register nc = new Register(stage);
//}
//});
}
public void buttonClick(){
Register nc = new Register(stage);
}
public static void main(String[] args) {
launch(args);
}
}
This is the register screen:
package Computing;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.Window;
public class Register {
Stage stage;
public Register (Stage s){
stage = s;
}
public void start(Stage primaryStage){
primaryStage.setTitle("Registration");
GridPane gridPane = createRegisterPane();
addUIControls(gridPane);
Scene scene = new Scene(gridPane, 800, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
private GridPane createRegisterPane() {
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setPadding(new Insets(40, 40, 40, 40));
gridPane.setHgap(10);
gridPane.setVgap(10);
return gridPane;
}
private void addUIControls(GridPane gridPane) {
// Add Header
Label headerLabel = new Label("Registration Form");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 24));
gridPane.add(headerLabel, 0,0,2,1);
GridPane.setHalignment(headerLabel, HPos.CENTER);
GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));
// FULL NAME
Label nameLabel = new Label("Full Name : ");
gridPane.add(nameLabel, 0,1);
// FULL NAME TEXT
TextField nameField = new TextField();
nameField.setPrefHeight(40);
gridPane.add(nameField, 1,1);
// USERNAME
Label emailLabel = new Label("Username : ");
gridPane.add(emailLabel, 0, 2);
// EMAIL TEXT
TextField emailField = new TextField();
emailField.setPrefHeight(40);
gridPane.add(emailField, 1, 2);
// PASSWORD
Label passwordLabel = new Label("Password : ");
gridPane.add(passwordLabel, 0, 3);
// PASSWORD TEXT
PasswordField passwordField = new PasswordField();
passwordField.setPrefHeight(40);
gridPane.add(passwordField, 1, 3);
// SUBMIT BUTTON
Button submitButton = new Button("Submit");
submitButton.setPrefHeight(40);
submitButton.setDefaultButton(true);
submitButton.setPrefWidth(100);
gridPane.add(submitButton, 0, 4, 2, 1);
GridPane.setHalignment(submitButton, HPos.CENTER);
GridPane.setMargin(submitButton, new Insets(20, 0,20,0));
submitButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if(nameField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error", "Please enter your name.");
return;
}
if(emailField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error", "Please enter a Username");
return;
}
if(passwordField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error!", "Please enter a password");
return;
}
showAlert(Alert.AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Registration Successful!", "Welcome " + nameField.getText());
}
});
}
private void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
}
public static void main(String[] args) {
launch(args);
}
}
I've tried using this instead of the buttonClick method also I'm slightly confused as to why it won't work as before I used the same method using buttonClick to send the scene to the next screen
submitButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {

How to set Menubutton always on top of other component like HBox (which is draggable)

I have a parent VBox which holds a menu button and a draggable HBox. When I drag the HBox, the menu button is not responding (because the HBox is set over the menu button). How do I always set the menu button on top of the HBox if it is draggable?
HBoxandVBoxExampleupdated.java:
import DraggableNode;
import javafx.scene.chart.NumberAxis;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class HBoxandVBoxExampleupdated extends Application
{
static Pane pane = new Pane();
static DraggableNode node = new DraggableNode();
static NumberAxis noaxis = new NumberAxis();
static String ref = "HHHHHelllelelelellelellelelellelelelaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
static HBox nobox = new HBox();
static NumberAxis lineXAxis;
static String Style = "-fx-border-color: blue;\n"
+ "-fx-border-insets: 5;\n"
+ "-fx-border-width: 3;\n"
+ "-fx-border-style: dashed;\n";
static String Style1 = "-fx-border-color: red;\n"
+ "-fx-border-insets: 5;\n"
+ "-fx-border-width: 3;\n"
+ "-fx-border-style: dashed;\n";
#Override
public void start(Stage primaryStage) throws Exception
{
pane.setStyle(Style);
node.setStyle(Style1);
VBox mainbox = new VBox(80);
mainbox.setAlignment(Pos.CENTER);
mainbox.setPadding(new Insets(50, 30, 100, 50));
VBox hbox = new VBox(60);
hbox.setAlignment(Pos.CENTER); // default TOP_LEFT
HBox vbox1 = new HBox();
HBox vbox2 = new HBox(10);
HBox vbox3 = new HBox(20);
Button close = new Button("X");
Button close1 = new Button("X");
MenuButton vcfmenu = new MenuButton("Vcf");
vcfmenu.getItems().add(new CheckMenuItem("About This Track"));
vcfmenu.getItems().add(new CheckMenuItem("Ping To Tap"));
vcfmenu.getItems().add(new CheckMenuItem("Edit Config"));
vcfmenu.getItems().add(new CheckMenuItem("Delete Track"));
vcfmenu.getItems().add(new CheckMenuItem("Save Track Data"));
vcfmenu.getItems().add(new CheckMenuItem("Show Labels"));
vcfmenu.getItems().add(new CheckMenuItem("Hides Sites Passing All Filters"));
vcfmenu.getItems().add(new CheckMenuItem("Hides Sites not Passing All Filters"));
vbox2.getChildren().add(vcfmenu);
for (String s : ref.split("")) {
Label l = new Label(s);
l.setBorder(new Border(
new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));
l.setBackground(
new Background(
new BackgroundFill(
(s.equals("N") ? Color.web("#DDDDDD")
: (s.equals("A") ? Color.web("#00BF00")
: (s.equals("C") ? Color.web("#0099FF")
: (s.equals("T") ? Color.web("#F00")
: Color.web("#D5BB04"))))),
CornerRadii.EMPTY, Insets.EMPTY)));
l.setAlignment(Pos.CENTER);
l.setPadding(new Insets(1, 4, 1, 4));
vbox1.getChildren().add(l);
}
lineXAxis = new NumberAxis(1, ref.length(), 4);
nobox.getChildren().add(lineXAxis);
nobox.setHgrow(lineXAxis, Priority.ALWAYS);
mainbox.getChildren().addAll(vbox2);
hbox.getChildren().addAll(nobox, vbox1);
node.getChildren().add(hbox);
pane.getChildren().addAll(node, mainbox);
Scene scene = new Scene(pane, 1150, 250);
primaryStage.setTitle("HBox and VBox Example");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
Application.launch(args);
}
}
DraggableNode.java:
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
public class DraggableNode extends StackPane {
private double x = 0;
private double y = 0;
private double mousex = 0;
private double mousey = 0;
private Node view;
private boolean dragging = false;
private boolean moveToFront = true;
private double size = 0;
private double newSize = 0;
public DraggableNode() {
init();
}
public DraggableNode(Node view) {
this.view = view;
getChildren().add(view);
setMouseTransparent(true);
init();
}
private void init() {
onMousePressedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
getScene().setCursor(Cursor.HAND);
// record the current mouse X and Y position on Node
mousex = event.getSceneX();
mousey = event.getSceneY();
x = getLayoutX();
y = getLayoutY();
if (isMoveToFront()) {
toFront();
}
}
});
onMouseDraggedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
double offsetX = event.getSceneX() - mousex;
x += offsetX;
double scaledX = x;
System.out.println(" : " + scaledX);
if (scaledX > 0)
{
return;
}
setLayoutX(scaledX);
dragging = false;
mousex = event.getSceneX();
event.consume();
}
});
onMouseClickedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
dragging = false;
}
});
}
/**
* #return the dragging
*/
protected boolean isDragging() {
return dragging;
}
/**
* #return the view
*/
public Node getView() {
return view;
}
/**
* #param moveToFront
* the moveToFront to set
*/
public void setMoveToFront(boolean moveToFront) {
this.moveToFront = moveToFront;
}
/**
* #return the moveToFront
*/
public boolean isMoveToFront() {
return moveToFront;
}
public void removeNode(Node n) {
getChildren().remove(n);
}
}
You set the DraggableNode to the front in the EventHandler for onMousePressedProperty. This puts DraggableNode on top of its sibling nodes and prevents the menu button from receiving mouse inputs.
To prevent this, I see two options:
don't set the DraggableNode to the front by setting moveToFront = false or, if that isn't possible,
set the DraggableNode to the back again after dragging by adding
onMouseReleasedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
toBack();
}
});
to the init method of DraggableNode.
For a more general solution, you could add a property to DraggableNode
private BooleanProperty dragInProcessProperty = new SimpleBooleanProperty(false);
public BooleanProperty dragInProcessProperty() {
return this.dragInProcessProperty;
}
Set the property to true while dragging in onMouseDraggedProperty and to false when the mouse is released
onMouseReleasedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
dragInProcessProperty.set(false);
}
});
and add a ChangeListener to the dragInProgressProperty in HBoxandVBoxExampleupdated
node.dragInProcessProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue.booleanValue()) {
mainbox.toFront();
}
}
});
to set the node to the front whenever dragging is finished.

Resources