Reputation: 11
public class Matrices extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
String inputValue = JOptionPane.ShowInputDialogue("Enter a value: ");
}
public static void main (String[] args){
launch(args);
}
}
This runs the program infinitely and doesn't display the JOptionPane dialogue box to ask the user for input
Upvotes: 1
Views: 676
Reputation: 159546
Why you shouldn't use a JOptionPane
Don't use a JOptionPane
in a JavaFX application.
JOptionPane
is for the Swing library, not the JavaFX library.
Generally, you should not mix Swing and JavaFX code unless you have a really good reason for it, and even then you must be careful about how you manage the integration (e.g. thread management) to ensure the best outcome.
Use a JavaFX Dialog
Instead of JOptionPane
, use a JavaFX Dialog
or Alert
.
For your particular case, you are using the JOptionPane
to gather input, so the equivalent JavaFX dialog for this is a TextInputDialog
.
Why your app doesn't exit
As to why the application doesn't complete, see the Application
documentation:
Waits for the application to finish, which happens when either of the following occur:
- the application calls Platform.exit()
- the last window has been closed and the implicitExit attribute on Platform is true
As you never show a JavaFX window and close it and you never call Platform.exit()
, the application never shuts down.
This issue doesn't arise when you show a TextInputDialog
, because that is a JavaFX window. After you enter a value and close the input dialog, the application will shut down automatically (if the dialog was the only window currently being shown for the application).
Working Example
Here is an example which uses TextInputDialog
instead of JOptionPane
:
import javafx.application.Application;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;
import java.util.Optional;
public class TextInputDialogExample extends Application {
private Optional<String> getValueFromUser() {
TextInputDialog dialog = new TextInputDialog("xyzzy");
dialog.setTitle("Value Input");
dialog.setHeaderText("Enter a value:");
dialog.setContentText("Value:");
return dialog.showAndWait();
}
@Override
public void start(Stage stage) {
Optional<String> value = getValueFromUser();
value.ifPresent(System.out::println);
}
public static void main(String args[]) {
launch(args);
}
}
Upvotes: 3