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
}
Related
This picture is all my code for the pop-ups I currently have.
I want to make it so that when a user goes to enter their name (If they want, if not it defaults to Player 1/ Player 2) and they enter a number instead, it will give another pop-up saying they can't put in a number.
You'll want to use a JTextField in the JOptionPane. Essentially, you'll need to create a JTextField, add a KeyListener to the field, and show a messageDialog with the field. If we use an inputDialog, two fields will show. I have developed the code below.
JTextField field = new JTextField("Player 1 Name"); //Create a new JTextField with the text "Player 1 Name"
field.addKeyListener(new KeyListener() { //Add a KeyListener
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) { //Called when key is pressed
String input = Character.toString(e.getKeyChar()); //Create string input which is equal to the key pressed
if(input.equals("1") || input.equals("2") || input.equals("3") || input.equals("4") || input.equals("5") || input.equals("6") || input.equals("7") || input.equals("8") || input.equals("9") || input.equals("0")){ //If the string equals any number
JOptionPane.showMessageDialog(null, "Numbers are not allowed!", "Error", JOptionPane.ERROR_MESSAGE); //Show a message dialog notifying the user
field.setText(field.getText().substring(0, field.getText().length() - 1)); //Eliminate the number inputed
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
JOptionPane.showMessageDialog(null, field, "Player Name", JOptionPane.INFORMATION_MESSAGE) //Show MessageDialog with the input field as the JTextField
You may use the same JTextField for all the dialogs so you won't have to copy the code twice. Hope this helped!
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// <--- !!
);
I would like to know how to not allow the user to change the screen's size. Also, can you please explain in details how to add a confirmation message "Are you sure you want to quit the program?", because there's a file that i want to creat if the user chooses "Yes". I tried to read about it, but i didn't quiet get it. I couldn't understand where to call the method that displays the message.
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
JOptionPane.showMessageDialog(this,"All operation have been saved ");
System.exit(0);}
}
Making a JFrame not resizable: frame.setResizable(false)
Doing something when the user closes the frame : read about the onClose listener here
EDIT: you also need to read about Dialogs here
First detect closing window event then show yor confirmation dialog
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Object[] options = {"Yes, please","No, thanks"};
int n = JOptionPane.showOptionDialog(this,"Would you like some green eggs to go "
+ "with that ham?",
"A Silly Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if(n==0){
//Yes, please
}else{
//No, thanks
}
}
});
this will result the following dialog
you can see the complete documentation here
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This is the code, which helps to display confirm dialog box on screen, First if statement just checks which radio button are pressed, than a confirm dialog box appears, On which there is option available , which is "ok" and "cancel". So when I click either "ok" or "Cancel" another confirm dialog box appears, which must have to show message, which shows which one is clicked, but there is an error, even if I click "ok" , it shows you pressed cancel
if (Choose == okCancel.getText() && IconChoose == NoneRadioButton.getText())
{
int response =
JOptionPane.showConfirmDialog(null, txt, " Message Dialog Box",
JOptionPane.OK_CANCEL_OPTION);
}
else if (response == JOptionPane.OK_OPTION)
{
JOptionPane.showConfirmDialog(null, "You Pressed OK ","",
JOptionPane.DEFAULT_OPTION);
}
if (response == JOptionPane.CANCEL_OPTION)
{
JOptionPane.showConfirmDialog(null, "You Pressed CANCEL ","",
JOptionPane.DEFAULT_OPTION);
}
try to use
.equals() or equalsIgnoreCase();
instaed of ==
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