Creating Dialog from JOptionPane and working on OK_CANCEL_OPTION [duplicate] - java

This question already has answers here:
Java Dialog - Find out if OK is clicked?
(4 answers)
Closed 6 years ago.
I have a custom dialog box that collects two strings from the user. I use OK_CANCEL_OPTION for the option type when creating the dialog. Evertyhings works except when a user clicks cancel or closes the dialog it has the same effect has clicking the OK button.
How can i handle the cancel and close events?
Heres the code I'm talking about:
JTextField topicTitle = new JTextField();
JTextField topicDesc = new JTextField();
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog = pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
// Do something here when OK is pressed but just dispose when cancel is pressed.
/Note: Please Don't Suggest me the way of JOptionPane.ShowOptionDialog(*****);** for this issue because i know that way but i need above mentioned way of doing and setting actions for "OK" and "CANCEL" buttons.*/

This works for me:
...
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog = pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
if(null == pane.getValue()) {
System.out.println("User closed dialog");
}
else {
switch(((Integer)pane.getValue()).intValue()) {
case JOptionPane.OK_OPTION:
System.out.println("User selected OK");
break;
case JOptionPane.CANCEL_OPTION:
System.out.println("User selected Cancel");
break;
default:
System.out.println("User selected " + pane.getValue());
}
}

According to the documentation you can use pane.getValue() to know which button was clicked.
From documentation:
Direct Use: To create and use an JOptionPane directly, the standard pattern is roughly as follows:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
dialog.show();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
//If there is not an array of option buttons:
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
//If there is an array of option buttons:
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;
Hope it helps,

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

Java - Validation of TextField

(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

show input dialog box after error message dialog box

I need to display an input dialog box and enter the player's name.
If the player clicked the ok button and the value of the input dialog is either a number or null an error should be displayed. If the player clicks the ok button of the error message dialog box, the input box will appear again.
I don't know if my code is wrong. I forgot how to code in java because of my web programming subject.
int[] player = new int[1];
for(int a =0; a<player.length; a++){
String input = JOptionPane.showInputDialog("Enter your Name:",JOptionPane.OK_CANCEL_OPTION);
try {
if(!input.matches("[a-zA-Z]+")){
JOptionPane.showMessageDialog(null,"Use Letters only", "Warning", JOptionPane.OK_OPTION);
} else {
input = String.valueOf(player[a]);
category c = new category();
this.dispose();
c.show();
}
}
catch(Exception e){
};
If you do the loop right, you'll need only one dialog:
String message = "Enter Your Name:";
String playerName = null;
do {
playerName =
JOptionPane.showInputDialog(message);
message = "<html><b style='color:red'>Enter Your Name:</b><br>"
+ "Use letters only.";
} while(playerName != null && !playerName.matches("[a-zA-Z]+"));
System.out.println("PlayerName: " + playerName);
This will include the error message into the next iteration of asking for a valid name. Makes it a bit nicer to work with as well.
Shows like this on first call:
and like this in case of errors:
Note
You might want to change your regex to "[a-zA-Z]\\w+" if numbers later on in the name are okay (for instance "bunny99")
Show an error dialog that displays the message, 'alert':
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
Show an internal information dialog with the message, 'information':
JOptionPane.showInternalMessageDialog(frame, "information", "information", JOptionPane.INFORMATION_MESSAGE);
Show an information panel with the options yes/no and message 'choose one':
JOptionPane.showConfirmDialog(null,"choose one", "choose one", JOptionPane.YES_NO_OPTION);
Show an internal information dialog with the options yes/no/cancel and message 'please choose one' and title information:
JOptionPane.showInternalConfirmDialog(frame, "please choose one", "information",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
Show a warning dialog with the options OK, CANCEL, title 'Warning', and message 'Click OK to continue':
Object[] options = { "OK", "CANCEL" };
JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options, options[0]);
Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");
Show a dialog asking the user to select a String:
Object[] possibleValues = { "First", "Second", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,"Choose one", "Input",JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]);

How do I close this JOptionPane upon clicking?

My JOptionPane shows up just fine, but when I click the button, nothing happens. Once I click the 'X', the console will print which of the buttons was clicked. It just won't close when the button is clicked:
final JOptionPane newDocWarning = new JOptionPane("Would you like to save before opening a new file?", JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
final JDialog newDocDialog = new JDialog(this, "New Document", true);
newDocDialog.setContentPane(newDocWarning);
newDocDialog.setSize(420, 150);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
newDocDialog.setLocation(dim.width/2-newDocDialog.getSize().width/2, dim.height/2- newDocDialog.getSize().height/2);
newDocDialog.setVisible(true);
int value = ((Integer)newDocWarning.getValue()).intValue();
if(value == JOptionPane.YES_OPTION){
System.out.println("YES OPTION WAS CLICKED");
newDocDialog.dispose();
}else if(value == JOptionPane.NO_OPTION){
System.out.println("NO OPTION WAS CLICKED");
newDocDialog.setVisible(false);
}else if(value == JOptionPane.CANCEL_OPTION){
System.out.println("CANCEL OPTION WAS CLICKED");
newDocWarning.setVisible(false);
}
Can you try this one using JOptionPane.showConfirmDialog()
int value = JOptionPane.showConfirmDialog(frame,
"Would you like to save before opening a new file?", "New Document",
JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
In this case you don't need to close it. It will be automatically closed once any button is clicked.
For more info have a look at How to Make Dialogs.

how to listen to Enter button when using JOptionPane.showOptionDialog

I use:
char[] password = null;
JPasswordField jpf = new JPasswordField(30);
java.lang.Object [] messageInput = { prompt, jpf };
java.lang.Object [] options = { jpf , "OK", "Cancel"};
int result = JOptionPane.showOptionDialog(null, messageInput, title,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, "");
JOptionPane.showMessageDialog(null,
result);
if (result == 1) {
password = jpf.getPassword();
}
else if(result == JOptionPane.CANCEL_OPTION)
{
}
return password;
to get password, but this can not listen to the Enter button.
I know if I set the options parameter to null, can make the dialog listen to "enter" button, but if I do that, the dialog don't focus to the textbox when show up.
Can someone help me on this?
I know if I set the options parameter to null, can make the dialog listen to "enter" button, but if I do that, the dialog don't focus to the textbox when show up.
Dialog Focus should help you out.

Categories