How do I close this JOptionPane upon clicking? - java

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.

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

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

Creating Dialog from JOptionPane and working on OK_CANCEL_OPTION [duplicate]

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,

JOptionPane showConfirmDialog with only one button

I need to have only one button in showConfirmDialog.
I tried this:
int response = JOptionPane.showConfirmDialog(null, "Time Entered Successfully",
"", JOptionPane.OK_OPTION, JOptionPane.PLAIN_MESSAGE);
if (response == JOptionPane.CLOSED_OPTION || response == JOptionPane.OK_OPTION)
{
System.out.println("CLOSING>>>>>>");
}
But this shows dialog with Yes_No_option.
I want only OK button to be displayed there. Is it possible?
try using this, it creates only one button
JOptionPane.showMessageDialog(null, "Loading Complete...!!!");
I want only OK button to be displayed there. Is it possible?
Use showOptionDialog() method.
Object[] options = {"OK"};
int n = JOptionPane.showOptionDialog(frame,
"Message here ","Title",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
It's the JOptionPane.DEFAULT_OPTION
JOptionPane.showConfirmDialog(null,
"MESSAGE",
"TITLE",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE);

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