Java - Validation of TextField - java

(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

Related

How do I make a JOptionPane dropdown that has a preset option that is not choosable?

Say I am making a program that keeps track of people's favorite food. I have a dropdown, as such:
String foods = { "Pizza", "Burgers", "Pasta", "Bacon" };
String favoriteFood = JOptionPane.showInputDialog(null, "What is your favorite food?", "Choice", JOptionPane.QUESTION_MESSAGE, null, foods, foods[0]));
JOptionPane.showMessageDialog(null, favoriteFood);
How do I make a part in the dropdown that is like "Choose now...", but if you click the "Choose now...", it doesn't become your choice? Thank you!
You may do it like this
String[] foods = { "Pizza", "Burgers", "Pasta", "Bacon" };
JComboBox<String> cb = new JComboBox<String>(foods);
cb.getModel().setSelectedItem("Choose now...");
cb.addHierarchyListener(hEv -> {
if((hEv.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && cb.isShowing()) {
JButton ok = SwingUtilities.getRootPane(cb).getDefaultButton();
ok.setEnabled(cb.getSelectedIndex() >= 0);
cb.addActionListener(aEv -> ok.setEnabled(cb.getSelectedIndex() >= 0));
} });
JPanel p = new JPanel(new GridLayout(0, 1, 0, 8));
p.add(new JLabel("What is your favorite food?"));
p.add(cb);
int choice = JOptionPane.showConfirmDialog(null,
p, "Choice", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
JOptionPane.showMessageDialog(null,
choice == JOptionPane.OK_OPTION? cb.getSelectedItem(): "no choice");
The first challenge is to set a (pre)selected value that is not part of the selectable choices. When you call setSelectedItem on a non-editable JComboBox, it will reject any values outside the model. However, we can set the selected value on the model directly, like in cb.getModel().setSelectedItem("Choose now...");
Then, to ensure that we won’t confuse this initial selection with an actual selection, we have to disable the “Ok” button until a choice from the list has been made (cb.getSelectedIndex() >= 0). To get the “Ok” button itself, we wait until the entire AWT hierarchy has been constructed and get the default button.
A possible solution using the JOptionPane is shown below. In this code the JDialog is more or less manually created. The OK button and available options are then pulled from the JOptionPane and the OK button is only enabled when anything other than 'Choose from...' is selected.
String[] foods = new String[]{"Choose now...", "Pizza", "Burgers", "Pasta", "Bacon"};
JOptionPane pane = new JOptionPane("What is your favorite food?", JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, null,
null, null);
pane.setWantsInput(true);
pane.setSelectionValues(foods);
pane.setInitialSelectionValue(foods[0]);
// create the dialog and select the initial value
JDialog dialog = pane.createDialog( null, "title" );
pane.selectInitialValue();
// find the OK Button and disable it by default
JPanel buttonPanel = (JPanel) pane.getComponent( 1 );
JButton ok = (JButton) buttonPanel.getComponent( 0 );
ok.setEnabled( false );
// find the JComboBox (the panel holding the available options)
JPanel childPanel = (JPanel) ((JPanel) pane.getComponent( 0 )).getComponent( 0 );
JPanel innerPanel = (JPanel) childPanel.getComponent( 1 );
JComboBox options = (JComboBox) innerPanel.getComponent( 1 );
// add an action listener to the JComboBox; enable the OK button if a valid option is selected
options.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ( options.getSelectedIndex() == 0 ) {
ok.setEnabled( false );
} else {
ok.setEnabled( true );
}
}
});
// show the dialog
dialog.show(); // <--- note this one is deprecated, should probably use: dialog.setVisible( true );
dialog.dispose();
// get the selected value
String value = pane.getInputValue().toString();

How to access outside variables in an action event handler (javafx button)?

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.

Get Multiple Results from Custom Dialog -- JavaFX

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
});

Java GUI - JOptionPane/JDialog customization issue

So I'm trying to make a simple dialog where the user can input some information... My problem is that I'm trying to make the whole background white; I got MOST of it, but there's a gray line behind the buttons that I don't know how to fix (make white as well). How can I fix it? :(
What it looks like:
What I want:
Code:
JPanel all = new JPanel();
all.setLayout(new BorderLayout());
all.add(names, BorderLayout.NORTH);
all.add(academic, BorderLayout.CENTER);
all.setBackground(Color.WHITE);
all.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); //int top, int left, int bottom, int right
Object [] options = {"SAVE", "EXIT"};
JOptionPane jop = new JOptionPane(all, JOptionPane.PLAIN_MESSAGE , JOptionPane.YES_NO_OPTION, null, options, null);
final JDialog dialog = jop.createDialog(null, "Username Information");
jop.setBackground(Color.WHITE);
dialog.setBackground(Color.WHITE);
dialog.setLocation(585, 300);
dialog.setVisible(true);
String choice = (String) jop.getValue();

Update the JLabel's label text during the event - Swing

Basically I want change the JLabel's Label text during on-click the button
'Generate PDF Record Book'
From the previous example says:
label.setText("new value");
when I do that, the label value doesn't change at all, please give me some directions, thanks
initialize();
JLabel lblNewLabel = new JLabel("513 k bytes");
lblNewLabel.setBounds(407, 713, 151, 14);
frmViperManufacturingRecord.getContentPane().add(lblNewLabel);
On button Generate PDF Record Book click
JButton btnGeneratePdfHeader = new JButton("Generate PDF Record Book");
btnGeneratePdfHeader.setMnemonic('G');
btnGeneratePdfHeader.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JLabel lblNewLabel = new JLabel("513 k bytes");
//java.io.File file = new java.io.File(strdfile);
//lblNewLabel.setSize(file.length());
//System.out.println(file.length());
String fileSize = file.length() + " k bytes";
System.out.println("I am here");
lblNewLabel.setText("new value");
}
});
You are creating a new JLabel when pressing the button and then set the text of that label to "new value"
final JLabel lblNewLabel = new JLabel("513 k bytes");
lblNewLabel.setText("new value");
rather than changing the text of the label on your UI. You will need to call setText("new value") on a reference to the label you've already added to the UI instead. For instance, that label would neeed to be a field in your UI class, eg final JLabel fileSizeLabel and you would set that labels text by calling
fileSizeLabel.setText("new value");
inside the buttons action listener.

Categories