Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
The community reviewed whether to reopen this question 3 days ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Look this:
https://code.makery.ch/blog/javafx-dialogs-official/ -> https://code.makery.ch/blog/javafx-dialogs-official/login-dialog.png
Tell me how to expand the width of the TextField (username, password) to the right end
Сode:
// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Login Dialog");
dialog.setHeaderText("Look, a Custom Login Dialog");
// Set the icon (must be included in the project).
dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));
// Set the button types.
ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField username = new TextField();
username.setPromptText("Username");
PasswordField password = new PasswordField();
password.setPromptText("Password");
grid.add(new Label("Username:"), 0, 0);
grid.add(username, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(password, 1, 1);
// Enable/Disable login button depending on whether a username was entered.
Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
// Do some validation (using the Java 8 lambda syntax).
username.textProperty().addListener((observable, oldValue, newValue) -> {
loginButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> username.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(username.getText(), password.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
result.ifPresent(usernamePassword -> {
System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
});
grid.setPadding(new Insets(20, 10, 10, 10));
grid.getColumnConstraints().addAll(new ColumnConstraints(), new ColumnConstraints(300));
Related
I'm a bit of a javafx noob. I want to make it so this button updates the "GraphView" object called "viewGraph", but I don't know how to properly do this because I can't access outside variables in the setOnAction event. I would also want to make startVertice and endVertice outside of the event class as well but I don't know how to do that.
I would think the answer would be to somehow pass the variables in using parameters but I don't know how to do that.
I tried looking stuff up and trying random syntax stuff but I still dont know what to do. It seems simple though.
WeightedGraph<Campus> graph = new WeightedGraph<>(vertices, edges);
Label startCampus = new Label("Starting Campus: ");
Label endCampus = new Label(" Ending Campus: ");
TextField startText = new TextField();
TextField endText = new TextField();
Button displayShortestPathBtn = new Button("Display Shortest Path");
HBox input = new HBox();
input.getChildren().addAll(startCampus, startText, endCampus, endText, displayShortestPathBtn);
input.setPadding(new Insets(25, 0, 0, 0));
VBox vbox = new VBox();
GraphView viewGraph = new GraphView(graph);
vbox.getChildren().addAll(viewGraph, input);
vbox.setPadding(new Insets(50, 50, 25, 50));
displayShortestPathBtn.setOnAction((event) -> {
int startVertice = Integer.parseInt(startText.getText());
int endVertice = Integer.parseInt(endText.getText());
WeightedGraph<Campus>.ShortestPathTree shortestPathGraph = graph.getShortestPath(startVertice);
ArrayList<Integer> path = (ArrayList)shortestPathGraph.getPath(endVertice);
/*
What I want to do:
viewGraph = new GraphView(graph, path);
*/
});
primaryStage.setTitle("Final Exam");
primaryStage.setScene(new Scene(vbox));
primaryStage.show();
I just want to be able to access the outside variables but idk if that's possible or if I'm approaching the problem correctly in the first place.
I have a JavaFX dialog, and it seems the content of the grid don't span the entire width of the dialog. Right now it spans to a MAXIMUM of the the left side of the dialog, to the width of the OK button. I'd like to either remove the white space to the right of my input fields. Or span the entire width.
I've tried:
Setting the min-width of the gridpane
Setting the min-width of the textfields
Setting the width of the stage
I'm pretty much at a loss here.
Here's my code!
// Create the custom dialog.
Dialog dialog = new Dialog<>();
dialog.initOwner(mainStage);
// Set Custom Icon
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image(Constants.kApplicationIcon));
dialog.getDialogPane().getStylesheets().add(Constants.kRootStylesheet);
dialog.getDialogPane().getStyleClass().add("accountDialog");
dialog.setTitle("New User Detected");
dialog.setHeaderText("Please complete user registration!");
// Set the button types.
ButtonType loginButtonType = new ButtonType("Create Account", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
grid.setAlignment(Pos.CENTER);
grid.setId("accountGrid");
TextField firstName = new TextField("First Name");
TextField lastName = new TextField("Last Name");
TextField email = new TextField("Email");
TextField gender = new TextField("Gender");
firstName.setId("textField");
lastName.setId("textField");
firstName.setPromptText("");
lastName.setPromptText("");
gender.setPromptText("");
email.setPromptText("");
email.setId("textField");
gender.setId("textField");
ToggleGroup studentRadioGroup = new ToggleGroup();
RadioButton mentorRadio = new RadioButton("Mentor");
RadioButton studentRadio = new RadioButton("Student");
studentRadio.fire();
mentorRadio.setToggleGroup(studentRadioGroup);
studentRadio.setToggleGroup(studentRadioGroup);
grid.add(new Label("First Name:"), 0, 0);
grid.add(firstName, 1, 0);
grid.add(new Label("Last Name:"), 0, 1);
grid.add(lastName, 1, 1);
grid.add(new Label("Email:"), 0, 2);
grid.add(email, 1, 2);
grid.add(new Label("Gender:"), 0, 3);
grid.add(gender, 1, 3);
GridPane.setHalignment(grid, HPos.CENTER);
GridPane.setHalignment(studentRadio, HPos.CENTER);
GridPane.setHalignment(studentRadio, HPos.CENTER);
grid.add(studentRadio, 0, 4);
grid.add(mentorRadio, 1, 4);
grid.setGridLinesVisible(true);
// Enable/Disable login button depending on whether a username was entered.
Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
// Do some validation (using the Java 8 lambda syntax).
firstName.textProperty().addListener((observable, oldValue, newValue) -> {
loginButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the firstname field by default.
Platform.runLater(firstName::requestFocus);
Optional<ButtonType> result = dialog.showAndWait();
ArrayList<String> data = new ArrayList<>();
System.out.println(result.get().toString());
if (result.get().getButtonData() == ButtonBar.ButtonData.OK_DONE) {
data.add("TRUE");
data.add(firstName.getText());
data.add(lastName.getText());
data.add(email.getText());
data.add(gender.getText());
data.add(mentorRadio.isSelected() ? "TRUE" : "FALSE");
} else {
data.add("FALSE");
}
return data;
Here's an image of the result. I want to again; either remove all the whitespace to the right of my grid, or span my grid to fit the whole width.
Image of Result
You are creating that extra space with grid.setPadding(new Insets(20, 150, 10, 10));. That 150 is the right padding. See the Insets documentation.
The GridPane is resized to it's preferred size. The padding on the right of 150 prevents the TextFields from growing larger in this direction.
grid.setPadding(new Insets(20, 150, 10, 10)); // sets right padding to 150
If you want to grow the TextFields to the maximum size the Labels/RadioButton to the left leaves, you should use ColumnConstraints to specify, that the second column should always grow:
ColumnConstraints constraints = new ColumnConstraints();
constraints.setHgrow(Priority.ALWAYS);
grid.getColumnConstraints().addAll(new ColumnConstraints(), constraints);
It's also possible to specify the preferred width of the second column via the ColumnConstraints object.
To test the behaviour when the window size changes, you could make the dialog resizeable:
dialog.setResizable(true);
To see the area the GridPane covers it could be helpful to assign a background:
grid.setStyle("-fx-background-color: red;");
Have you tried the setExpandableContent() method from the dialog's pane? You can pass in whatever node you like, and then it should be able to resize to fit the entire Alert.
An example of setting a GridPane as the Alert's content.
GridPane() grid = new GridPane();
Alert alert = new Alert(AlertType.INFORMATION);
alert.getDialogPane().setExpandableContent(grid);
Left side of picture: It is when it is run directly from intellij
Right side of picture: Created fat jar (which is created by the feature called "Jar with dependencies") is run as double click from mouse
As you can see, Checkboxes are not aligned .Every component is created by code not from fxml...What can be the cause of this?
Edit:
First of all, width and height are fixed. Thus they will never change. I disabled Them Below you can find the code.
HBox row1 = new HBox(10);
//row1.setPadding();
Label nameLbl = new Label("Login Email");
nameLbl.setPrefWidth(DefaultValues.LABEL_WIDTH);
nameLbl.setPadding(new Insets(4,0,0,0));
txtEmail = new TextField();
txtEmail.setPrefSize(DefaultValues.TEXTAREA_WIDTH,20);
txtEmail.focusedProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue)
checkLicence();
});
row1.getChildren().addAll(nameLbl,txtEmail);
HBox row2 = new HBox(10);
Label passwordLbl = new Label("Password");
passwordLbl.setPrefWidth(DefaultValues.LABEL_WIDTH);
passwordLbl.setPadding(new Insets(4,0,0,0));
txtPassword = new PasswordField();
txtPassword.setPrefSize(DefaultValues.TEXTAREA_WIDTH,20);
row2.getChildren().add(passwordLbl);
row2.getChildren().add(txtPassword);
HBox row3 = new HBox(10);
//row1.setPadding();
Label refreshTime = new Label("Refresh Time");
refreshTime.setPrefWidth(DefaultValues.LABEL_WIDTH);
refreshTime.setPadding(new Insets(4,0,0,0));
txtRefreshTime = new TextField();
txtRefreshTime.setPrefSize(DefaultValues.TEXTAREA_WIDTH,20);
txtRefreshTime.setPromptText("Seconds");
txtRefreshTime.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")) {
txtRefreshTime.setText(newValue.replaceAll("[^\\d]", ""));
}
});
row3.getChildren().add(refreshTime);
row3.getChildren().add(txtRefreshTime);
HBox row3_1 = new HBox(10);
//row1.setPadding();
Label userCountLbl = new Label("User Count(for point calc.)");
userCountLbl.setPrefWidth(DefaultValues.LABEL_WIDTH);
userCountLbl.setPadding(new Insets(4,0,0,0));
txtUserCountForPointCalc = new TextField();
txtUserCountForPointCalc.setPrefSize(DefaultValues.TEXTAREA_WIDTH,20);
txtUserCountForPointCalc.setPromptText("Not very important");
txtUserCountForPointCalc.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")) {
txtUserCountForPointCalc.setText(newValue.replaceAll("[^\\d]", ""));
}
});
row3_1.getChildren().add(userCountLbl);
row3_1.getChildren().add(txtUserCountForPointCalc);
HBox row4 = new HBox(10);
//row1.setPadding();
Label showNotifications = new Label("Show Notifications");
showNotifications.setPrefWidth(DefaultValues.LABEL_WIDTH - 10);
showNotifications.setPadding(new Insets(4,0,0,0));
cbShowNotifications = new CheckBox();
cbShowNotifications.setPrefWidth(180);
Button btnClearNotificationCache = new Button("Clear Notification Cache");
btnClearNotificationCache.setOnAction(e -> {
notifiedAssignedToMeTickets.clear();
notifiedUnassignedTickets.clear();
});
row4.setAlignment(Pos.CENTER_LEFT);
row4.getChildren().addAll(showNotifications,cbShowNotifications,btnClearNotificationCache);
HBox row5 = new HBox(10);
//row1.setPadding();
Label autoReplyCompanies = new Label("Auto-Reply Companies");
autoReplyCompanies.setPrefWidth(DefaultValues.LABEL_WIDTH);
autoReplyCompanies.setPadding(new Insets(4,0,0,0));
txtAutoReplyCompanies = new TextField();
txtAutoReplyCompanies.setPrefSize(DefaultValues.TEXTAREA_WIDTH,20);
txtAutoReplyCompanies.setPromptText("(For Unassigned Tickets..)Seperate with ';' for multiple companies");
row5.getChildren().add(autoReplyCompanies);
row5.getChildren().add(txtAutoReplyCompanies);
//txtAutoReplyModules
HBox row5_2 = new HBox(10);
//row1.setPadding();
Label autoReplyModules = new Label("Auto-Reply Modules");
autoReplyModules.setPrefWidth(DefaultValues.LABEL_WIDTH);
autoReplyModules.setPadding(new Insets(4,0,0,0));
txtAutoReplyModules = new TextField();
txtAutoReplyModules.setPrefSize(DefaultValues.TEXTAREA_WIDTH,20);
txtAutoReplyModules.setPromptText("(For Unassigned Tickets..)Seperate with ';' for multiple modules");
row5_2.getChildren().add(autoReplyModules);
row5_2.getChildren().add(txtAutoReplyModules);
HBox row6 = new HBox(10);
//row1.setPadding();
Label autoReplyMessage = new Label("Auto-Reply Message");
autoReplyMessage.setPrefWidth(DefaultValues.LABEL_WIDTH);
autoReplyMessage.setPadding(new Insets(4,0,0,0));
txtAutoReplyMessage = new TextArea();
txtAutoReplyMessage.setPrefSize(DefaultValues.TEXTAREA_WIDTH,65);
row6.getChildren().add(autoReplyMessage);
row6.getChildren().add(txtAutoReplyMessage);
//cbStatistics
HBox row6_1 = new HBox(10);
Label searchStatistics = new Label("Process Statistics");
searchStatistics.setPrefWidth(DefaultValues.LABEL_WIDTH - 10);
searchStatistics.setPadding(new Insets(4,0,0,0));
cbStatistics = new CheckBox();
cbStatistics.setSelected(true);
cbStatistics.setPrefWidth(180);
row6_1.getChildren().addAll(searchStatistics,cbStatistics);
HBox row7 = new HBox(10);
//row1.setPadding();
Label searchUnassignedsLbl = new Label("Search Unassigned Tickets");
searchUnassignedsLbl.setPrefWidth(DefaultValues.LABEL_WIDTH - 10);
searchUnassignedsLbl.setPadding(new Insets(4,0,0,0));
cbSearchUnassigneds = new CheckBox();
cbSearchUnassigneds.setSelected(true);
cbSearchUnassigneds.setPrefWidth(180);
//row7.setAlignment(Pos.CENTER_LEFT);
row7.getChildren().addAll(searchUnassignedsLbl,cbSearchUnassigneds);
HBox row8 = new HBox(10);
//row1.setPadding();
Label searchAssignedToMe = new Label("Search Replied to u");
searchAssignedToMe.setPrefWidth(DefaultValues.LABEL_WIDTH);
searchAssignedToMe.setPadding(new Insets(4,0,0,0));
cbSearchAssignedToMeTickets = new CheckBox();
cbSearchAssignedToMeTickets.setSelected(true);
cbSearchAssignedToMeTickets.setPrefSize(DefaultValues.TEXTAREA_WIDTH,20);
row8.getChildren().add(searchAssignedToMe);
row8.getChildren().add(cbSearchAssignedToMeTickets);
HBox row9 = new HBox(10);
Label checkUpdateLbl = new Label("Check Updates");
checkUpdateLbl.setPrefWidth(DefaultValues.LABEL_WIDTH - 10);
checkUpdateLbl.setPadding(new Insets(4,0,0,0));
cbCheckUpdates = new CheckBox();
cbCheckUpdates.setSelected(checkUpdatesSetting);
cbCheckUpdates.setPrefWidth(180);
Button btnUpdateUpdater = new Button("Update Updater");
btnUpdateUpdater.setOnAction(event -> downloadUpdaterUpdate());
//btnUpdateUpdater.setPadding(new Insets(5));
row9.setAlignment(Pos.CENTER_LEFT);
row9.getChildren().addAll(checkUpdateLbl,cbCheckUpdates,btnUpdateUpdater);
HBox row10 = new HBox();
Label dummy = new Label("");
dummy.setPrefWidth(DefaultValues.LABEL_WIDTH);
Button btnSaveSettings = new Button("Save Settings");
btnSaveSettings.setOnAction(e -> {
if(txtEmail.getLength() == 0 || txtPassword.getLength() == 0 || txtRefreshTime.getLength() == 0)
showAlert(Alert.AlertType.ERROR,"","ilk 3 alan boş olamaz");
else{
Task<Void> task = new Task<Void>() {
#Override
protected Void call(){
shutDownCalled = true;
waitExecutorShutDown();
checkLicence();
Settings st = new Settings();
st.setEmail(txtEmail.getText().trim());
st.setPassword(txtPassword.getText().trim());
st.setRefreshTime(Integer.parseInt(txtRefreshTime.getText().trim()));
st.setUserCountForPointCalculation(txtUserCountForPointCalc.getLength() == 0 ? DefaultValues.userCountForPointCalculation : Integer.parseInt(txtUserCountForPointCalc.getText()));
st.setShowNotifications(cbShowNotifications.isSelected());
st.setAutoReplyCompanies(txtAutoReplyCompanies.getText().trim());
st.setAutoReplyModules(txtAutoReplyModules.getText().trim());
st.setAutoReplyMessage(txtAutoReplyMessage.getText().trim());
st.setSearchUnassignedTickets(cbSearchUnassigneds.isSelected());
st.setSearchAssignedToMeTickets(cbSearchAssignedToMeTickets.isSelected());
st.setCheckUpdates(cbCheckUpdates.isSelected());
st.setProcessStatistics(cbStatistics.isSelected());
Settings.saveNormalBotSettingsToFile(st);
settings = st;
needLogin = true;
initData(false);
return null;
}
};
new Thread(task).start();
mainTabs.getSelectionModel().select(0);
}
});
row10.getChildren().addAll(dummy,btnSaveSettings);
VBox vb = new VBox(9);
vb.setPadding(new Insets(10,10,0,10));
vb.getChildren().addAll(row1,row2,row3,row3_1,row5,row5_2,row6,row6_1,row4,row7,row8,row9,row10);
return vb;
An HBox makes no guarantee about the amount of space it actually assigns to any child node that is contained inside it. It merely guarantees to place them in order, with a minimum gap if you specify a spacing, and makes a best effort to size each child node to its preferred size. Many factors which are beyond your control will affect the actual size of each node, including font sizes (which depend on the available fonts), total size available to the HBox, etc etc. All these may change depending on the platform the application is running on, including depending on the JDK version.
So trying to line things up vertically by placing them in a collection of HBoxs and setting the preferred sizes of the child nodes is simply not a reliable way to approach this (and is not designed as such). The problem is there is no real way to connect the layout of one HBox to the layout of another HBox: they are all laid out independently. If you want to lay components out so they are aligned relative to each other both horizontally and vertically, you should use a GridPane, which is specifically designed for that purpose.
It is generally a very bad idea (not just in JavaFX; this applies to most UI toolkits) to hard-code sizes of anything, so anytime you are using this as a solution, there is almost certainly a better approach.
The basic idea behind using a GridPane would look like:
GridPane grid = new GridPane();
// padding around entire grid:
grid.setPadding(new Insets(4);
grid.setHgap(10);
grid.setVgap(9);
Label nameLbl = new Label("Login Email");
// column 0, row 0:
grid.add(nameLbl, 0, 0);
txtEmail = new TextField();
txtEmail.focusedProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue)
checkLicence();
});
// column 1, row 0, span 2 columns:
grid.add(txtEmail, 1, 0, 2, 1);
// ...
Label searchAssignedToMe = new Label("Search Replied to u");
// column 0, row 7:
grid.add(searchAssignedToMe, 0, 7);
cbSearchAssignedToMeTickets = new CheckBox();
cbSearchAssignedToMeTickets.setSelected(true);
// column 1, row 7, span two columns:
grid.add(cbSearchAssignedToMeTickets, 1, 7, 2, 1);
Label checkUpdateLbl = new Label("Check Updates");
// column 0, row 8:
grid.add(checkUpdateLbl, 0, 8);
cbCheckUpdates = new CheckBox();
cbCheckUpdates.setSelected(checkUpdatesSetting);
// column 1, row 8:
grid.add(cbCheckUpdates, 1, 8);
Button btnUpdateUpdater = new Button("Update Updater");
btnUpdateUpdater.setOnAction(event -> downloadUpdaterUpdate());
// column 2, row 8:
grid.add(btnUpdateUpdater, 2, 8);
// ...
Button btnSaveSettings = new Button("Save Settings");
btnSaveSettings.setOnAction(...);
// center button horizontally in its cells (it spans the whole row):
GridPane.setHalignment(btnSaveSettings, HPos.CENTER);
// column 0, row 9, span 3 columns:
grid.add(btnSaveSettings, 0, 9, 3, 1);
You can completely configure how any potential extra space is allocated among the columns (using ColumnConstraints instances), among the rows (using RowConstraints instances), and how the controls are aligned within their individual cell(s). You can also specify these on a node-by-node basis if you need.
You probably want, for example, hgrow of the three columns to be SOMETIMES, SOMETIMES, and ALWAYS; you may need to set the fillWidth of the TextInputControls to true.
See the GridPane documentation, which explains this all completely.
(SOLVED) Issue 1: I am trying to add a simple verification to my 2 TextFields by checking its values. However, with this code below, I think whats happening is that the try/catch is called as the program starts up (which I tested with the System.out.println() code), therefore always resulting in an error. How can I make it such that this is called only after button 'Finish' is pressed?
(UNSOLVED) Issue 2: Following on from my first issue, how can I make it such that if either my if or my try/catch returns an 'error', then pressing the 'Finish' button doesn't end the code?
Code:
Dialog<Pair<String, Integer>> dialog = new Dialog();
dialog.setTitle("Add new values");
dialog.setHeaderText("Please input name and number");
ButtonType finishButton = new ButtonType("Finish", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(finishButton, ButtonType.CANCEL);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
TextField name = new TextField();
name.setPromptText("Name");
TextField size = new TextField();
number.setPromptText("Number");
grid.add(new Label("Name:"), 0, 1);
grid.add(eventName, 1, 1);
grid.add(new Label("Number:"), 0, 3);
grid.add(eventSize, 1, 3);
dialog.getDialogPane().setContent(grid);
//verification code below
if (eventName.getText() == null || eventName.getText() == "") {
grid.add(new Label("Name is required!"), 0, 0);
}
try {
int size = Integer.parseInt(eventSize.getText());
} catch (NumberFormatException e) {
grid.add(new Label("Size is required!"), 0, 1);
System.out.println("Test failed");
}
This is the code I am trying to learn off from: Here
Firstly, you must compare Strings using the .equals() method. I believe, but am not 100% certain, that the check for null is unnecessary. So, change:
if (eventName.getText() == null || eventName.getText() == "")
to
if (eventName.getText().equals(""))
I am unfamiliar with the Dialog class. However, when I need to implement something like this I like to use JDialog, and put it in a while loop:
JPanel p = new JPanel(new GridLayout(2,2));
JTextField nameField = new JTextField(5);
JTextField numberField = new JTextField(5);
JLabel nameLabel = new JLabel("Name");
JLabel numberLabel = new JLabel("Number");
p.add(nameLabel);
p.add(nameField);
p.add(numberLabel);
p.add(numberField);
while(true){
int result = JOptionPane.showConfirmDialog(null, p, "Please enter Name and Number.", JOptionPane.OK_CANCEL_OPTION);
if(result == JOptionPane.OK_OPTION){
if(nameField.getText().equals("")){
JOptionPane.showConfirmDialog(null, "Invalid input!");
}
else break;
}
}
This code should guide you on how you might be able to check for different inputs, and validate them accordingly. See JOptionPane for more details on the different dialogs you can open.
Hope this helps you.
Dont know if this will help but i made a button that sounds like what your trying to do
//taking input from pop up box
JTextField InputPosX = new JTextField(5);
JTextField InputNegX = new JTextField(5);
JTextField InputY = new JTextField(5);
JPanel ChangeAxisPanel = new JPanel();
ChangeAxisPanel.add(new JLabel("Max X:"));
ChangeAxisPanel.add(InputPosX);
ChangeAxisPanel.add(Box.createHorizontalStrut(15)); // a spacer
ChangeAxisPanel.add(new JLabel("Min X:"));
ChangeAxisPanel.add(InputNegX);
ChangeAxisPanel.add(Box.createHorizontalStrut(15)); // a spacer
ChangeAxisPanel.add(new JLabel("Y:"));
ChangeAxisPanel.add(InputY);
int result = JOptionPane.showConfirmDialog(null, ChangeAxisPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
//if ok is pressed
if (result == JOptionPane.OK_OPTION) {
if(!(InputPosX.getText().isEmpty())){
defaultPosX=Integer.parseInt(InputPosX.getText());
}
if(!(InputNegX.getText().isEmpty())){
defaultNegX=Integer.parseInt(InputNegX.getText());
}
if(!(InputY.getText().isEmpty())){
defaultY=Integer.parseInt(InputY.getText());
}
}
}
});
most of this was gathered from
Here its a good link for gui input windows. also if you are looking for a simpler method you may want to look into jbutton's you can use it to call this window
Jbutton
anyways hope this helped
I've got a little problem with my JavaFX code. I'm sure you all know that you can get the input from a TextInputDialog with an Optional< String > and .showAndWait(). But what should I do when I have a custom dialog with multiple TextFields and a ChoiceBox? How do I get the results from all of them when clicking OK? I thought about a List<String> but I didn't manage to do it..
Code (Custom Dialog):
public class ImageEffectInputDialog extends Dialog {
private ButtonType apply = new ButtonType("Apply", ButtonBar.ButtonData.OK_DONE);
private ButtonType cancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
public ImageEffectInputDialog(String title) {
setTitle(title);
setHeaderText(null);
GridPane dPane = new GridPane();
Label offsetX = new Label("Offset X: ");
Label offsetY = new Label("Offset Y: ");
Label color = new Label("Shadow Color: ");
TextField offsetXText = new TextField();
TextField offsetYText = new TextField();
ChoiceBox<String> shadowColors = new ChoiceBox<>();
shadowColors.getItems().add(0, "Black");
shadowColors.getItems().add(1, "White");
dPane.setHgap(7D);
dPane.setVgap(8D);
GridPane.setConstraints(offsetX, 0, 0);
GridPane.setConstraints(offsetY, 0, 1);
GridPane.setConstraints(offsetXText, 1, 0);
GridPane.setConstraints(offsetYText, 1, 1);
GridPane.setConstraints(color, 0, 2);
GridPane.setConstraints(shadowColors, 1, 2);
dPane.getChildren().addAll(offsetX, offsetY, color, offsetXText, offsetYText, shadowColors);
getDialogPane().getButtonTypes().addAll(apply, cancel);
getDialogPane().setContent(dPane);
}
}
Code (where I want the results)
if(scrollPane.getContent() != null && scrollPane.getContent() instanceof ImageView) {
// ImageEffectUtil.addDropShadow((ImageView) scrollPane.getContent());
ImageEffectInputDialog drop = new ImageEffectInputDialog("Drop Shadow");
//Want the Results here..
}
I hope someone might be able to help.
First of all, in order to obtain different values of different types (generic solution) just define a new data structure, say Result, which contains fields like offsetX, offsetY and whatever else you need. Next, extend Dialog<Result> instead of just Dialog. Finally, in the constructor of your ImageEffectInputDialog you need to set result converter, as follows:
setResultConverter(button -> {
// here you can also check what button was pressed
// and return things accordingly
return new Result(offsetXText.getText(), offsetYText.getText());
});
Now wherever you need to use the dialog, you can do:
ImageEffectInputDialog dialog = new ImageEffectInputDialog("Title");
dialog.showAndWait().ifPresent(result -> {
// do something with result object, which is of type Result
});