JavaFX open new window - javafx-2

Looking at this code they show a way to display a new window after a login. When username and password are correct it opens new dialog. I want a button click to open new dialog, without checking for username and password.

If you just want a button to open up a new window, then something like this works:
btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Parent root;
try {
root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
Stage stage = new Stage();
stage.setTitle("My New Stage Title");
stage.setScene(new Scene(root, 450, 450));
stage.show();
// Hide this current window (if this is what you want)
((Node)(event.getSource())).getScene().getWindow().hide();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

I use the following method in my JavaFX applications.
newWindowButton.setOnMouseClicked((event) -> {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
});

The code below worked for me I used part of the code above inside the button class.
public Button signupB;
public void handleButtonClick (){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
}

Related

Platform.runLater() method

I'm trying to understand, whether Platform.runLater() method invokes just the SAME JavaFxApplicationThread, as in start()-method or ANOTHER, PARALLEL thread with the same name?
In the code below:
1) first, start()-method was invoked with JavaFxApplicationThread;
2) then, startFilling()-method was invoked, where new thread starts;
3) at last, new Stage was opened with method openMessage(), where Platform.runLater() method was used.
Please see the code:
public class FillingTimeLine extends Application {
private LongProperty lp = new SimpleLongProperty(0);
private Timeline timeline = new Timeline();
#Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
System.out.println("\nSTARTING THREAD: " + Thread.currentThread().getName());
StackPane spane = new StackPane();
ProgressBar pb = new ProgressBar(0);
pb.setMinSize(160, 21.5);
pb.setMaxSize(160, 21.5);
pb.setPrefSize(160, 21.5);
pb.progressProperty().bind(lp.divide(10000 * 1.0));
pb.setStyle("-fx-base:darkgray;-fx-accent:red;");
spane.getChildren().add(pb);
Scene scene = new Scene(spane, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
startFilling();
openNewStage();
}
public void startFilling() throws InterruptedException {
new Thread(() -> {
System.out.println("\nSTARTING THREAD: " + Thread.currentThread().getName());
timeline = new Timeline(new KeyFrame(Duration.seconds(0), new KeyValue(lp, 0)),
new KeyFrame(Duration.seconds(20), new KeyValue(lp, 20000)));
if (Thread.currentThread().isInterrupted()) {
System.out.println("\n THR WAS INTERRUPTED!");
return;
}
timeline.play();
try {
Thread.sleep(20000);
} catch (InterruptedException ex) {
System.out.println("\n THR WAS INTERRUPTED!");
return;
}
}).start();
}
public void stopFilling() {
new Thread(() -> {
System.out.println("\nSTOPPING THREAD: " + Thread.currentThread().getName());
timeline.stop();
}).start();
}
public void openNewStage() {
Platform.runLater(() -> {
System.out.println("\nOPENNING THREAD" + Thread.currentThread().getName());
Stage qst = new Stage();
StackPane sp = new StackPane();
Button btn = new Button("STOP");
btn.setMaxHeight(25);
btn.setMinHeight(25);
btn.setPrefHeight(25);
btn.setMaxWidth(80);
btn.setMinWidth(80);
btn.setPrefWidth(80);
btn.setAlignment(Pos.CENTER);
btn.setOnAction(e -> {
try {
qst.close();
stopFilling();
} catch (Exception e1) {
return;
}
});
sp.getChildren().add(btn);
Scene scene = new Scene(sp, 200, 120);
qst.setX(50);
qst.setY(50);
qst.setScene(scene);
qst.setResizable(false);
qst.show();
});
}
public static void main(String[] args) {
launch(args);
}
}
I thougt Platform.runLater() enables parallel execution. And I expected, that new Stage with a STOP-button would be opened by another thread, because JavaFxApplicationThread was still busy with primaryStage.
But CONSOLE PUTPUT shows that new Stage was opened also with JavaFxApplicationThread- just as primaryStage:
STARTING THREAD: JavaFX Application Thread
STARTING THREAD: Thread-3
OPENNING THREAD: JavaFX Application Thread
STOPPING THREAD: Thread-4
So how can one and the same thread open new Stage, if primaryStage is still showing and is not closed?
Or is OPENING THREAD - another, parallel thread with the same name?
Thank you in advance

JavaFX task not reruning once canceled or finishing once

I am working on a basic Java FX task exercise. It counts from 1 to 150 on a thread. The current value is presented on a label and updates a progress bar.
There is a button to start the task, to cancel it and to view canceled status of the task.
The thing that puzzles me is as to why I cannot re run the task after having canceled the thread once(same thing happens if I let the task finnish).
I want to be able to rerun the task . Then I need to make it so that it will resume(though that shouldn't be that hard after figuring out how to rerun the task)
Source ;
public class JavaFX_Task extends Application {
#Override
public void start(Stage primaryStage) {
final Task task;
task = new Task<Void>() {
#Override
protected Void call() throws Exception {
int max = 150;
for (int i = 1; i <= max; i++) {
if (isCancelled()) {
break;
}
updateProgress(i, max);
updateMessage(String.valueOf(i));
Thread.sleep(100);
}
return null;
}
};
ProgressBar progressBar = new ProgressBar();
progressBar.setProgress(0);
progressBar.progressProperty().bind(task.progressProperty());
Label labelCount = new Label();
labelCount.textProperty().bind(task.messageProperty());
final Label labelState = new Label();
Button btnStart = new Button("Start Task");
btnStart.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
new Thread(task).start();
}
});
Button btnCancel = new Button("Cancel Task");
btnCancel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
task.cancel();
}
});
Button btnReadTaskState = new Button("Read Task State");
btnReadTaskState.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
labelState.setText(task.getState().toString());
}
});
VBox vBox = new VBox();
vBox.setPadding(new Insets(5, 5, 5, 5));
vBox.setSpacing(5);
vBox.getChildren().addAll(
progressBar,
labelCount,
btnStart,
btnCancel,
btnReadTaskState,
labelState);
StackPane root = new StackPane();
root.getChildren().add(vBox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The Task documentation is pretty clear on this.
As with FutureTask, a Task is a one-shot class and cannot be reused. See Service for a reusable Worker.
There is an example of restartable concurrent services in the Service documentation.

Stage is hidden when dialog is shown

I have this code which displays confirmation dialog to exit application.
public class DialogPanels
{
public void initClosemainAppDialog(final Stage primaryStage)
{
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent event)
{
event.consume(); // Do nothing on close request
// Dialog Stage init
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
// Frage - Label
Label label = new Label("Exit from the program");
// Button "Yes"
Button okBtn = new Button("Yes");
okBtn.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
//primaryStage.close();
//dialog.close();
//Platform.exit();
System.exit(0);
}
});
// Button "No"
Button cancelBtn = new Button("No");
cancelBtn.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
primaryStage.show();
dialog.close();
}
});
// Layout for the Button
HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setAlignment(Pos.CENTER);
hbox.getChildren().add(okBtn);
hbox.getChildren().add(cancelBtn);
// Layout for the Label and hBox
VBox vbox = new VBox();
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.getChildren().add(label);
vbox.getChildren().add(hbox);
// Stage
Scene scene = new Scene(vbox);
dialog.setScene(scene);
dialog.show();
}
});
}
}
The problem is that when close the main application the dialog box is displayed and the main stage is hidden. I want to display the dialog box in front of the main stage. Can you help me to correct this?
UPDATE
I tested this code, it's working but when the dialog is displayed the mainstage is not responsible(frozen). How I an make the mainstage responsible when I display dialog?
Consume the closing event and set the owner of the stage if you do not want to see another window when the windows are minimized:
#Override
public void handle(WindowEvent event)
{
event.consume(); // Do nothing on close request
// Dialog Stage init
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
// other stuff
}
});
You need to set the proper relationships between primaryStage and dialog stage. Here's a hint to get you going:
...
dialog.initOwner(primaryStage);
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.showAndWait();
You can find more information in Oracle's JavaFX 2 JavaDocs.
More example code (edit)
I'm using setOnHiding(..) instead of setOnCloseRequest(..):
stage.setOnHiding(new AskUserIfHeReallyWantsToQuitWindowHandler(stage));
I extracted your code into a seperate event handler class and fixed the issues I mentioned (sorry, I am little short on time right now):
public class AskUserIfHeReallyWantsToQuitWindowHandler implements EventHandler<WindowEvent> {
private final Stage primaryStage;
public AskUserIfHeReallyWantsToQuitWindowHandler(final Stage primaryStage) {
Objects.requireNonNull(primaryStage);
this.primaryStage = primaryStage;
}
#Override
public void handle(final WindowEvent event) {
event.consume();
final Stage dialog = new Stage();
final Button okBtn = new Button("Yes");
okBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent event) {
dialog.close();
primaryStage.close();
}
});
// Button "No"
final Button cancelBtn = new Button("No");
cancelBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent event) {
dialog.close();
Platform.runLater(new Runnable() {
#Override
public void run() {
primaryStage.show();
}
});
}
});
// Layout for the Button
final HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setAlignment(Pos.CENTER);
hbox.getChildren().add(okBtn);
hbox.getChildren().add(cancelBtn);
// Layout for the Label and hBox
final VBox vbox = new VBox();
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.getChildren().add(new Label("Do your really want to exit?"));
vbox.getChildren().add(hbox);
// Stage
final Scene scene = new Scene(vbox);
dialog.setScene(scene);
dialog.initOwner(primaryStage);
dialog.initModality(Modality.NONE);
dialog.showAndWait();
}
}

How to create modal dialog with image

I have this very simple modal dialog:
public class DialogPanels
{
public void initClosemainAppDialog(final Stage primaryStage)
{
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent event)
{
event.consume(); // Do nothing on close request
// Dialog Stage init
final Stage dialog = new Stage();
// If you want to freeze the background during dialog appearence set Modality.APPLICATION_MODAL
// or to allow clicking on the mainstage components set Modality.NONE
// and set dialog.showAndWait();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
// Frage - Label
Label label = new Label("Exit from the program");
// Button "Yes"
Button okBtn = new Button("Yes");
okBtn.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
//primaryStage.close();
//dialog.close();
//Platform.exit();
System.exit(0);
}
});
// Button "No"
Button cancelBtn = new Button("No");
cancelBtn.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
primaryStage.show();
dialog.close();
}
});
// Layout for the Button
HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setAlignment(Pos.CENTER);
hbox.getChildren().add(okBtn);
hbox.getChildren().add(cancelBtn);
// Layout for the Label and hBox
VBox vbox = new VBox();
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.getChildren().add(label);
vbox.getChildren().add(hbox);
// Stage
Scene scene = new Scene(vbox, 450, 150, Color.WHITESMOKE);
dialog.setScene(scene);
dialog.show();
}
});
}
}
I want to add image and to make it to look like this:
But I admin that it's too complex for my short knowledge to get the appropriate result. Can you show me how I can split the dialog, add second background and make my code to look the same as this example please?
Have a look at the ControlsFX project, they have some sophisticated dialogs and it's open source, so you can look up how it's done. For example, your dialog looks like this confirmation dialog of ControlsFX:
There is also support for custom dialogs.
€dit:
With the "show Masthead" option enabled it actually looks exactly like it:

Make menubar call method when it is clicked?

I am wanting to add an empty javafx.scene.control.Menu to a MenuBar and have it call a method when it is clicked.
I have tried using menu.setOnShowing(new EventHandler<Event>(){}); with no luck.
Here is what I am currently working with:
public MenuBar createMenuBar() {
MenuBar menuBar = new MenuBar();
Menu file = new Menu("File");
Menu addAccountTab = new Menu("Add Tab");
addAccountTab.setOnShowing(new EventHandler<Event>() {
public void handle(Event e) {
System.out.println("addAccountTab Menu clicked.");
}
});
menuBar.getMenus().add(addAccount);
return menuBar;
}
However, clicking the Menu does not call the onShowing event.
Your Menu needs to contain at least one MenuItem for the event to fire.
public class MenuApplication extends Application {
#Override
public void start(Stage primaryStage) {
MenuBar menuBar = new MenuBar();
Menu file = new Menu("File");
Menu addAccountTab = new Menu("Add Tab");
addAccountTab.setOnShowing(new EventHandler<Event>() {
#Override
public void handle(Event e) {
System.out.println("addAccountTab Menu clicked.");
}
});
MenuItem NewMenuItem = new MenuItem("New");
addAccountTab.getItems().add(NewMenuItem);
menuBar.getMenus().addAll(file, addAccountTab);
StackPane root = new StackPane();
root.getChildren().add(menuBar);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The output I get is shown below:
Although the API suggests otherwise, the onShowing event doesn't get called when there are no MenuItems in the Menu or when they are all hidden.
I was able to solve the issue by using Menu's hide() method inside of the onShown event like this.
public MenuBar createMenuBar() {
MenuBar menuBar = new MenuBar();
Menu addAccount = MenuBuilder.create()
.onShown(new EventHandler<Event>() {
public void handle(Event e) {
((Menu)e.getSource()).hide();
System.out.println("addAccount Clicked");
}
}).items(new MenuItem())
.text("Add Account").build();
menuBar.getMenus().addAll(addAccount);
return menuBar;
}

Resources