Get the return value of JOptionPane - java

My JOptionPane code is as follows:
selectedSiteName = JOptionPane.showInputDialog("Enter the name of the new site:");
This renders out an input with a textbox and an OK and Cancel button. I need to detect if Cancel was clicked.
Cheers.

Check if selectedSiteName == null . This will be the case if the user clicks Cancel or closes the dialog.

Read the JOptionPane API and follow the link to the Swing turorial on "How to Use Dialogs" for a working example.

if(selectedSiteName == JOptionPane.CANCEL_OPTION)
{
}
should work.

JOptionPane extends JComponent.
Methods of JOptionPane
1) .showMessageDialog(); // VOID :-(
2) .showInputDialog(); // return STRING :-)
3) .showConfirmDialog(); // return int :-)
-> and more...
Example:
void myMethod() {
JDialog jd = new JDialog();
jd.setDefaultCloseOperation(1);
JOptionPane jop = new JOptionPane();
int val = jop.showConfirmDialog(jd, "Hello");
if(val == 0) jop.showMessageDialog(null, "Success", "INFO", jop.INFORMATION_MESSAGE);
System.out.println(val);
jd.add(jop);
}
Helpful link:
- Why does JOptionPane.getValue() continue to return uninitializedValue
- https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

Related

Java showInputDialog select custom text

I have rename dialog for rename file
String renameTo = JOptionPane.showInputDialog(gui, "New Name", currentFile.getName());
it works this way, but I have a problem.
the problem is that I set the default value with the extension of the file
but I just want the file name to be selected.
sample : my file name = yusuf.png
I want select only yusuf like;
There is a lot going on inside JOptionPane, it's one of the things that makes it so powerful, it also makes it a little inflexible to.
Two immediate problems are apparent...
You can't gain direct access to the JTextField been used to get input from the user
The JOptionPane wants to control which components have focus when the dialog is first shown.
Setting up the JTextField is actually straight forward...
String text = "yusuf.png";
int endIndex = text.lastIndexOf(".");
JTextField field = new JTextField(text, 20);
if (endIndex > 0) {
field.setSelectionStart(0);
field.setSelectionEnd(endIndex);
} else {
field.selectAll();
}
This will basically select all the text from the start of the String up to the last . or all the text if no . can be found.
The difficult part now is taking back focus control from the JOptionPane
// Make a basic JOptionPane instance
JOptionPane pane = new JOptionPane(field,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null);
// Use it's own dialog creation process, it's simpler this way
JDialog dialog = pane.createDialog("Rename");
// When the window is displayed, we want to "steal"
// focus from what the `JOptionPane` has set
// and apply it to our text field
dialog.addWindowListener(new WindowAdapter() {
#Override
public void windowActivated(WindowEvent e) {
// Set a small "delayed" action
// to occur at some point in the future...
// This way we can circumvent the JOptionPane's
// focus control
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
field.requestFocusInWindow();
}
});
}
});
// Put it on the screen...
dialog.setVisible(true);
dialog.dispose();
// Get the resulting action (what button was activated)
Object value = pane.getValue();
if (value instanceof Integer) {
int result = (int)value;
// OK was actioned, get the new name
if (result == JOptionPane.OK_OPTION) {
String newName = field.getText();
System.out.println("newName = " + newName);
}
}
And, crossing our fingers, we end up with something looking like...
Personally, I'd wrap this up in a nice reusable class/method call which returned the new text or null based on the action of the user, but that's me
Isn't there an easier way?
Of course, I just like showing you the most difficult solution possible ... ๐Ÿ˜ณ (sarcasm) ... it's kind of why I suggested wrapping it up in it's own utility class, so you can re-use it later ๐Ÿ˜‰

how to capture ok button pressed from JOptionPane

I want to capture the ok button event when the "OK" button is pressed in on a JOptionPane. I then want to display a jframe. I've found numerous tutorials and videos on capturing all sorts of events except for the JOptionPane. The Java docs are not much help for a newbie. Hoping someone can help. I have the following.
JOptionPane.showMessageDialog(frame,
"Press OK to get a frame");
How do I implement the listener to capture the OK pressed event.
private class Listener implements ActionListener {
public void
actionPerformed(ActionEvent e) {
}
}
There's no need to capture it -- code flow will return immediately post the JOptionPane display line. If you want to know if OK vs cancel vs delete the window was pressed, then use a different JOptionPane -- use the JOptionPane.showConfirmDialog(...), and capture the result returned from this method call.
String text = "Press OK to get a frame";
String title = "Show Frame";
int optionType = JOptionPane.OK_CANCEL_OPTION;
int result = JOptionPane.showConfirmDialog(null, text, title, optionType);
if (result == JOptionPane.OK_OPTION) {
//...
}
You can't do it with the showMessageDialog method. You have to use the showConfirmDialog method instead. This will return you a value on which you can determine the button that was pressed:
int result = JOptionPane.showConfirmDialog(frame, "Press OK to get a frame");
if (result == JOptionPane.YES_OPTION) {
// Yes button was pressed
} else if (result == JOptionPane.NO_OPTION) {
// No button was pressed
}
To get the OK Button you need to use OK_CANCEL_OPTION:
int result = JOptionPane.showConfirmDialog(frame, "Press OK to get a frame",
"Title", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
// OK button was pressd
} else if (result == JOptionPane.CANCEL_OPTION) {
// Cancel button was pressed
}

JDialog dissappears when I switch between two windows

I'm trying to make a simple JDialog, which asks the user for input in the form of 3 text fields, and it displays correctly and its PropertyListener works perfectly fine, I haven't assigned a parent for the JDialog in it's constructor, so I'm guessing by default the parent is set to be the ancestor of all the components in my applet. However, when I change from the applet to, say a firefox window and when I click back on my applet, the JDialog has disappeared. Would I need to set a certain property to the JDialog to make sure it stays even when I switch windows. The starnge thing is that I think the dialog is still up, but invisible, because when another dialog appears after the first has disappeared, both dialog appear at once(the first dialog reappearing). MY code for the JDialog is just below:
private void addQuestion() {
questionTextField = new TextField(50);
Object[] componentsArray = {"Question:", questionTextField, "MQLYes:", mqlYesTextField, "MQLNo:", mqlNoTextField};
Object[] options = {"Enter", "Cancel"};
addQuestionDialog = new JDialog(new JFrame(),"Add question");
addQuestionPane = new JOptionPane(componentsArray, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
int x = getX() + getWidth()/2, y = getY() + getHeight()/2;
addQuestionDialog.setContentPane(addQuestionPane);
addQuestionDialog.setResizable(false);
addQuestionDialog.setSize(300,210);
addQuestionDialog.setVisible(true);
addQuestionDialog.setLocation(x, y);
addQuestionDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
addQuestionPane.addPropertyChangeListener(this);
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (addQuestionDialog.isVisible() && (e.getSource() == addQuestionPane) && (JOptionPane.VALUE_PROPERTY.equals(prop) || JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
Object value = addQuestionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
//ignore reset
return;
}
//Reset the JOptionPane's value.
//If you don't do this, then if the user
//presses the same button next time, no
//property change event will be fired.
addQuestionPane.setValue(
JOptionPane.UNINITIALIZED_VALUE);
if (value.equals("Enter")) {
String questionTypedText = questionTextField.getText();
String mqlYesTypedText = mqlYesTextField.getText();
String mqlNoTypedText = mqlNoTextField.getText();
sqlModel.addQuestion(questionTypedText, mqlYesTypedText, mqlNoTypedText);
questionTextField.setText("");
mqlYesTextField.setText("");
mqlNoTextField.setText("");
} else { //user closed dialog or clicked cancel
addQuestionDialog.setVisible(false);
}
}
}
I've checked the code several time and I don't see any issues with it, and the dialogs do what they're supposed to do, so I'm guessing there's a special addQuestion.set...(Object setValue) method which I should be adding in.
Would I need to set a certain property to the JDialog to make sure it stays even when I switch windows.
Yes.
I haven't assigned a parent for the JDialog in it's constructor,
and that would be the problem. The dialog will be visible whenever the owner of the dialog is visible, so you need to specify the owner JFrame.

JDialog box giving same result for both yes and no buttons/inputs

I have created a JDialog box to display some warning massage to the users. When the user gets the warning massage and if he clicks on yes button the application do some work and if the user selects no then he remains on the same place.
I am getting 0 value for yes and 1 value for no. But the JDialog box giving same result for both yes and no button i.e, application is getting close for both inputs. But what i wanted is if the user selects yes then the application do some thing and if he selects no then nothing happen(the UI window remain open).
public void warningMassage(String Text) {
int n = JOptionPane.showConfirmDialog(frame, Text, "Warning", JOptionPane.YES_NO_OPTION);
System.out.println(n);
if(n == 0){
System.exit(0);
System.out.println(JOptionPane.YES_OPTION);
} else {
frame.setVisible(true);
}
}//warningMassage
Use the below code
public void warningMassage(String yourText){
int n = JOptionPane.showConfirmDialog(
frame,
yourText,
"Warning",
JOptionPane.YES_NO_OPTION);
System.out.println(n);
if(n == JOptionPane.YES_OPTION){
frame.setVisible(true);
}
else{
System.exit(0);
System.out.println(JOptionPane.YES_OPTION);
}
}//warningMassage
A YES returns 0 and a NO returns 1
Documentation for the JDialog Box
Use
if(n==JOptionPane.YES_OPTION)
//yes pressed
else
//no pressed
JDialog box is not giving same result for both yes and no inputs
. if you choose No the frame does not close untill you press
on terminal or you explicitly set
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
As said by #Cool Guy I also prefer to use
if(n==JOptionPane.YES_OPTION)
//yes pressed
else
//no pressed
but currently at this time your problem is not this .Do Post your Main Class
JOptionPane.showConfirmDialog() with JOptionPane.YES_NO_OPTION can return:
JOptionPane.YES_OPTION: public static final int YES_OPTION = 0;
JOptionPane.NO_OPTION: public static final int NO_OPTION = 1;
You should use those const in your check:
if (JOptionPane.showConfirmDialog(...) == JOptionPane.YES_OPTION) {
// do something
}
However, a small hint: if you want to display a warning message, consider to use this:
JOptionPane.showConfirmDialog(
parentComponent,
message,
title,
optionType,
messageType
);
where messageType is an integer designating the kind of message this is; primarily used to determine the icon from the pluggable Look and Feel: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE.
Then, in your case:
JOptionPane.showConfirmDialog(
null,
"message",
"TITLE",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE// <--- !!
);

Java Swing JOptionPane Button Options

So this is my first time working with the JOptionPane and I was wondering if someone could help explain how I could make both of my buttons do certain actions? For all intent and purposes have it just print out "Hi". Here is my code. So far it only prints out "Hi" if I click the "Uhh...." button but I want it to do the same when I click the "w00t!!" button as well. I know it has something to do with the parameter "JOptionPane.YES_NO_OPTION" but I'm not sure what exactly I have to do with it. Thanks for the help in advance!
Object[] options = {"Uhh....", "w00t!!"};
int selection = winnerPopup.showOptionDialog(null,
"You got within 8 steps of the goal! You win!!",
"Congratulations!", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE, null,
options, options[0]);
if(selection == JOptionPane.YES_NO_OPTION)
{
System.out.println("Hi");
}
From the javadocs,
When one of the showXxxDialog methods returns an integer, the
possible values are:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION
So, your code should look something like,
if(selection == JOptionPane.YES_OPTION){
System.out.println("Hi");
}
else if(selection == JOptionPane.NO_OPTION){
System.out.println("wOOt!!");
}
But regardless, this logic is a bit bizarre so I would probably just roll my own dialog.
In JOPtionPane class there are some constants that represent the values โ€‹โ€‹of the buttons.
/** Return value from class method if YES is chosen. */
public static final int YES_OPTION = 0;
/** Return value from class method if NO is chosen. */
public static final int NO_OPTION = 1;
/** Return value from class method if CANCEL is chosen. */
public static final int CANCEL_OPTION = 2;
You changed the names of the buttons, and consequently, your first button "Uhh" has the value 0, and its button "w00t!" assumed a value of 1.
So, you can use this:
if(selection == JOptionPane.YES_OPTION)
{
System.out.println("Hi");
}
else if(selection == JOptionPane.NO_OPTION){
// do stuff
}
or maybe could be better use the swicht/case function:
switch (selection )
{
case 0:
{
break;
}
case 1:
{
break;
}
default:
{
break;
}
}
int selection = 0;
JOptionPane.showOptionDialog(null,
"You got within 8 steps of the goal! You win!!",
"Congratulations!", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE, null,
options, options[0]);
if(selection == JOptionPane.YES_NO_OPTION)
{
System.out.println("Hi");
}

Categories

Resources