JavaFX Stage.close() not calling my onCloseRequest() handler - javafx

Please refer to the JavaFX SSCCE below. The print statement appears when closing the primary stage from the window's default titlebar "X" button. The print statement does NOT appear when clicking the "Close" button. Why isn't my onCloseHandler being called when I call close() on the stage? Is my expectation somehow unreasonable or is this (yet another) bug in JavaFX? Thanks!
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button closeButton = new Button("Close");
closeButton.setOnAction(e -> {
primaryStage.close();
});
primaryStage.setOnCloseRequest(e -> {
System.out.println("onCloseRequest handler called!");
});
StackPane rootPane = new StackPane();
rootPane.getChildren().add(closeButton);
primaryStage.setScene(new Scene(rootPane, 300, 250));
primaryStage.show();
}
}

As described by the Javadoc, this is only fired on external requests:
Called when there is an external request to close this Window.
Maybe setOnHidden would work for you, it is called in both cases.
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button closeButton = new Button("Close");
closeButton.setOnAction(e -> {
primaryStage.close();
});
primaryStage.setOnHidden(e -> {
System.out.println("stage hidden");
});
StackPane rootPane = new StackPane();
rootPane.getChildren().add(closeButton);
primaryStage.setScene(new Scene(rootPane, 300, 250));
primaryStage.show();
}
}

Related

How to call the public void start(Stage primaryStage) Method from a different class

I'am new to JavaFX, so my coding is not the best. My programme has one Stage with 2 different Scenes. For a better overview I have created a new class for the second Scene. From this second Scene I want to go back to first one, using a button. The method: primaryStage.setScene(scene) is not working and I dont know why. Can someone please help me? :)
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
GridPane primarygridpane = new GridPane();
Scene scene = new Scene(primarygridpane,400,400);
...
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
public class Harnwegsinfektion {
public static void create (Stage primaryStage){
GridPane secondarygridpane = new GridPane();
Scene scene2 = new Scene(secondarygridpane,400,400);
buttonBack.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e) {
primaryStage.setScene(scene);
}
});
primaryStage.setScene(scene2);
primaryStage.show();
}
}
The problem is that your scene variable is named scene2 and you are calling setScene() with scene.
I don't really know when and where create() is called, but if you want to go back to the first scene from the button, you have to save the original one before switching :
public static void create (Stage primaryStage){
GridPane secondarygridpane = new GridPane();
Scene scene2 = new Scene(secondarygridpane,400,400);
Scene originalScene=primaryStage.getScene(); //save the previous scene
buttonBack.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e) {
primaryStage.setScene(originalScene); //go back to the previous scene
}
});
primaryStage.setScene(scene2);
primaryStage.show();
}

Add KeyEvent for calculator numpad in JavaFX using MVC

I created in Eclipse a simple calculator using JavaFx and MVC pattern. I would like to add keylisteners in order to press the buttons of my calculator by simply pressing the buttons in my keyboard. I tried to add #onKeyPress in SceneBuilder and then a method onKeypress (with some coding inside) in my Controller class but nothing happens.Could you please give some general instructions how to implement something like this? Thanks!
Thanks for your comments. I added the following code snippet in App.java:
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
controller.numFromKeyboard(event.getCode().toString());
}
});
And also, I had to add:
Parent root = loader.load();
Controller controller = loader.getController();
// The above line MUST be
// inserted after root is loaded in order the controller of my
// app to be instantiated,
// otherwise we will get a null exception when handler will be
// invoked
App.java
public class App extends Application {
//controller = new Controller();
#Override
public void start(Stage primaryStage) {
try {
// Read file fxml and draw interface.
FXMLLoader loader = new FXMLLoader(getClass()
.getResource("/application/View.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("/application/application.css").toExternalForm());
Image icon = new Image(getClass().getResourceAsStream("/application/Assets/App.png"));
primaryStage.getIcons().add(icon);
primaryStage.setTitle("JavaFX Calculator by Dimitris Baltas");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
controller.numFromKeyboard(event.getCode().toString());
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}

Switching between Scene JavaFX

I created a scene in class1, then i created a scene2 in class2.
How to switch between them?
public class class1 extends Application{
Stage window1;
BorderPane layout1;
Scene scene1;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
window1 = primaryStage;
window.setTitle("Stage 1");
// And here is a button which switchs between scenes or stages,
//i dont know what is better.So:
button.setOnAction(e -> ?????????)
scene1 = new Scene(layout1, 800,600);
window1.show();
}
}
And here is the second class in which i have another scene.
public class class2 extends Application{
Stage window2;
BorderPane layout2;
Scene scene2;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
window2 = primaryStage;
window2.setTitle("Stage 2");
scene2 = new Scene(layout, 800,600);
window2.show();
}
}
I wrote this controller to keep track of the different scenegraphes and switch the content of my Stage with no hassle.
Maybe you want to take a look at FXML:
http://docs.oracle.com/javafx/2/fxml_get_started/why_use_fxml.htm#CHDCHIBE
public class ScreenController {
private HashMap<String, Pane> screenMap = new HashMap<>();
private Scene main;
public ScreenController(Scene main) {
this.main = main;
}
protected void addScreen(String name, Pane pane){
screenMap.put(name, pane);
}
protected void removeScreen(String name){
screenMap.remove(name);
}
protected void activate(String name){
main.setRoot( screenMap.get(name) );
}
}
So I can write:
ScreenController screenController = new ScreenController(scene);
screenController.add("layout1", layout1 );
screenController.add("layout2", layout2 );
screenController.add("testSwitch", FXMLLoader.load(getClass().getResource( "TestSwitch.fxml" )));
button.setOnAction(e -> screenController.activate("layout2"));
This was a workaround for a fullscreen application, where the MacOS fullscreen transition was shown every time a stage switches its scene.
put this in your Controller. You can use anything (like button,label etc.) to get access to your Stage (best inside an eventhandler from Button).
Stage stage = (Stage) AnyThingOnScene.getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getResource("someFile.fxml"));
Scene scene = new Scene(root,420,360);
stage.setScene(scene);

JAVAFX Make dynamic textArea size

I'm making chat application using JAVAFX. The messages displayed in textArea, but the textArea always in the same size. How can I make the textArea to fit exactly to the amount of text? TNX
The following code does exactly what You wants
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
AnchorPane root = new AnchorPane();
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
TextArea ta=new TextArea();
ta.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
// your algorithm to change height
ta.setPrefHeight(ta.getPrefHeight()+10);
}
});
root.getChildren().add(ta);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}

JavaFX stage.setOnCloseRequest without function?

This is my Start-Methode. First i create a stage and set a title and a scene. And i wanna create a dialog if someone wants to close the window on the window-close-btn [X]. i thought i will catch this event with the setOnCloseRequest()-function. But i still can close all stages i open while runtime.
#Override
public void start(final Stage primaryStage) throws Exception {
primaryStage.setTitle("NetControl");
primaryStage.setScene(
createScene(loadMainPane())
);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(final WindowEvent event) {
//Stage init
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
// Frage - Label
Label label = new Label("Do you really want to quit?");
// Antwort-Button JA
Button okBtn = new Button("Yes");
okBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
dialog.close();
}
});
// Antwort-Button NEIN
Button cancelBtn = new Button("No");
cancelBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
primaryStage.show();
dialog.close();
}
});
}
});
primaryStage.show();
}
private Pane loadMainPane() throws IOException {
FXMLLoader loader = new FXMLLoader();
Pane mainPane = (Pane) loader.load(
getClass().getResourceAsStream(ContentManager.DEFAULT_SCREEN_FXML)
);
MainController mainController = loader.getController();
ContentManager.setCurrentController(mainController);
ContentManager.loadContent(ContentManager.START_SCREEN_FXML);
return mainPane;
}
private Scene createScene(Pane mainPane) {
Scene scene = new Scene(mainPane);
setUserAgentStylesheet(STYLESHEET_MODENA);
return scene;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
Are there any other functions to catch the window-events?
or isnt it logical to run the CloseRequest on the primaryStage, i read something with platforms (but i dont know if it necessary for my problem)?
In the onCloseRequest handler, call event.consume();.
That will prevent the primary stage from closing.
Remove the primaryStage.show(); call from the cancel button's handler and add a call to primaryStage.hide(); in the OK button's handler.

Resources