How to handle cancel button in JOptionPane - java

I had created a JOptionPane of type showInputDialog. When it opens it, it shows me two buttons: OK and Cancel. I would like to handle the action when I push on Cancel button, but I don't know how to reach it. How can I get it?

For example:
int n = JOptionPane.showConfirmDialog(
frame, "Would you like green eggs and ham?",
"An Inane Question",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
Alternatively with showOptionDialog:
Object[] options = {"Yes, please", "No way!"};
int n = JOptionPane.showOptionDialog(frame,
"Would you like green eggs and ham?",
"A Silly Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
See How to Make Dialogs for more details.
EDIT: showInputDialog
String response = JOptionPane.showInputDialog(owner, "Input:", "");
if ((response != null) && (response.length() > 0)) {
}

This is an old question, and I am an Java newbie so there might be better solutions, but I wanted to know the same, and maybe it can help others, what I did was to check if the response was null.
If the user clicks "cancel", the response will be null. If they click "ok" without entering any text the response will be the empty string.
This worked for me:
//inputdialog
JOptionPane inpOption = new JOptionPane();
//Shows a inputdialog
String strDialogResponse = inpOption.showInputDialog("Enter a number: ");
//if OK is pushed then (if not strDialogResponse is null)
if (strDialogResponse != null){
(Code to do something if the user push OK)
}
//If cancel button is pressed
else{
(Code to do something if the user push Cancel)
}

The showMessageDialog, shouldn't show two buttons, so something is amiss with either your code or your interpretation of it. Regardless, if you want to give the user an choice and want to detect that choice, don't use a showMessageDialog but rather a showConfirmDialog, and get the int returned and test it to see if it is JOptoinPane.OK_OPTION.

You could do it like this:
String val = JOptionPane.showInputDialog("Value: ");
if(val == null){
// nothing goes here if yo don't want any action when canceled, or
// redirect it to a cancel page if needed
}else{
//insert your code if ok pressed
// JOptionPane return an String, as you was talking about int
int value = Integer.ParseInt(val);
}

showInputDialog return NULL if you click cancel and String object even if it's empty.
So all you need to do is test if it's Null and if it's not empty.

package Joptionpane;
import javax.swing.JOptionPane;
public class Cancle_on_JOptionPane {
public static void main(String[] args) {
String s;
int i;
for (i=0;i<100;i++){
s = JOptionPane.showInputDialog(null,"What is your favorite fruit ?");
try {
if (s.equals("")) {
JOptionPane.showMessageDialog(null," Enter your answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=2;
} else {
JOptionPane.showMessageDialog(null," s = "+s," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Cancle answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
}
}

This may be your answer:
package Joptionpane;
import javax.swing.JOptionPane;
public class Cancle_on_JOptionPane {
public static void main(String[] args) {
String s;
int i;
for(i=0;i<100;i++){
s = JOptionPane.showInputDialog(null,"What is your favorite fruit ?");
try{
if(s.equals("")) {
JOptionPane.showMessageDialog(null," Enter your answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=2;
}
else {
JOptionPane.showMessageDialog(null," s = "+s," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Cancle answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
}
}

Related

How check radio buttons checked or not?

I have tried simple java programme using if statements.
for that, I'm using radio buttons to check whether is check or not?
please check my code below is not working properly someone please help me on this?
Project link below
https://drive.google.com/file/d/1xhNbKyXYJh2k5i7a6nVl1VkTY7dTNzSg/view?usp=sharing
private void BTN_submitActionPerformed(java.awt.event.ActionEvent evt) {
String finalResult;
int age = Integer.parseInt(TXT_age.getText());
RBTN_male.setActionCommand("male");
RBTN_female.setActionCommand("female");
String radio_Result = BTNgrp_gender.getSelection().getActionCommand();
if (RBTN_male.isSelected() || RBTN_female.isSelected()) {
if (TXT_age.getText() == null || TXT_age.getText().trim().isEmpty()) {
JOptionPane optionPane = new JOptionPane("Please fill your age", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("Age missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
} else {
if (age == 0) {
JOptionPane optionPane = new JOptionPane("Please enter valid age", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("Wrong age");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
} else {
if (age > 0 && age <= 5) {
finalResult = "Rhymes";
LBL_result.setText(finalResult);
} else if (age > 15) {
finalResult = "Poetry";
LBL_result.setText(finalResult);
}
}
}
} else {
JOptionPane optionPane = new JOptionPane("Please Select Your Gender", JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("Gender Missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
The main problem with your code is in the second line of your method BTN_submitActionPerformed
int age = Integer.parseInt(TXT_age.getText());
Here the value for TXT_age is “Enter your age”. Now this cannot be parsed to an integer therefore a NumberFormatException is thrown which prevents the program from continuing its expected course of execution. The program also removes the placeholder text from this field on click leaving it empty i.e “” therefore submitting it will also result in an error.
To solve the issues above you can rewrite this method as follows:
private void BTN_submitActionPerformed(java.awt.event.ActionEvent evt) {
int age;
String finalResult;
JOptionPane optionPane;
JDialog dialog;
RBTN_male.setActionCommand("male");
RBTN_female.setActionCommand("female");
try {
age = Integer.parseInt(TXT_age.getText());
if (RBTN_male.isSelected() || RBTN_female.isSelected()) {
if (age == 0 || age < 0 ) {
optionPane = new JOptionPane("Please enter valid age", JOptionPane.ERROR_MESSAGE);
dialog = optionPane.createDialog("Wrong age");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
} else {
if (age > 0 && age <= 5) {
finalResult = "Rhymes";
LBL_result.setText(finalResult);
} else if (age > 15) {
finalResult = "Poetry";
LBL_result.setText(finalResult);
}
}
} else {
optionPane = new JOptionPane("Please Select Your Gender", JOptionPane.ERROR_MESSAGE);
dialog = optionPane.createDialog("Gender Missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
} catch (NumberFormatException e) {
optionPane = new JOptionPane("Please fill your age", JOptionPane.ERROR_MESSAGE);
dialog = optionPane.createDialog("Age missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
On a sidenote you can also think of other problems that may arise. For example, as user can enter anything in the textfield that means a user can enter a number that may not fit in an int. So if that happens then your program will again break. However, if you make above mentioned changes to your method then the problems that you are facing currently will be resolved.

Checking for words in a loop

So I have this project for my computer class and I can't seem to get my program to run no matter how many different ways I try it. What I'm trying to do is have the program check if what the user types equals any of the three words (Cookies, Milk, Both) and if it doesn't ask the question again and use that input but since I'm new to java I can't seem to get it to work
Here's my code:
import javax.swing.*;
import java.util.*;
public class Cookie {
public static void main(String[] args) {
try {
Info info = new Info();
} catch(Exception e) {
System.err.println("Error! " + e.getMessage());
}
}
static class Info {
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
String word1 = "Cookies";
String word2 = "milk";
String word3 = "Both";
String flagger = "";
while (true)
if(inputs.length() !=0) {
}
for(int i=0; i<inputs.length(); i++)
{
for(int j=0; j<word1.length(); j++)
{
if(inputs.charAt(i)==word1.charAt(j))
{
flagger=flagger+word1.charAt(i)+"";
}
}
for(int j=0; j<word2.length(); j++)
{
if(inputs.charAt(i)==word2.charAt(j))
{
flagger=flagger+word2.charAt(i)+"";
}
}
for(int j=0; j<word3.length(); j++)
{
if(inputs.charAt(i)==word3.charAt(j))
{
flagger=flagger+word3.charAt(i)+"";
}
}
if(!(inputs.equalsIgnoreCase(flagger))) {
String message = String.format("%s", "Huh, I didn't get that, please say it again");
JOptionPane.showMessageDialog(null, message);
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
}
if(inputs.equalsIgnoreCase("cookies")) {
String message = String.format("%s", "Here have some Cookies :)");
JOptionPane.showMessageDialog(null, message);
}
if(inputs.equalsIgnoreCase("MILK")) {
String message = String.format("%s", "Here is the Milk you wanted :)");
JOptionPane.showMessageDialog(null, message);
}
if(inputs.equalsIgnoreCase("BOTH")) {
String message = String.format("%s", "Here is your Cookies and Milk :)");
JOptionPane.showMessageDialog(null, message);
}
}
}
}
}
}
I was able to compile your code after making few fixes. I have used a different approach, this is working, at least for most of the scenarios.
Here's my Cookie.java
public class Cookie {
public static void main(String[] args) {
try {
Info info = new Info();
info.checkInput();
} catch(Exception e) {
System.err.println("Error! " + e.getMessage());
}
}
}
And Info.java
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
public class Info {
public void checkInput() {
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
Map<String, String> words = new HashMap<String, String>();
words.put("cookies", "Here have some Cookies :)");
words.put("milk", "Here is the Milk you wanted :)");
words.put("both", "Here is your Cookies and Milk :)");
while (true) {
if (inputs != null && inputs.length() > 0) {
if (words.containsKey(inputs.toLowerCase())) {
JOptionPane.showMessageDialog(null,
words.get(inputs.toLowerCase()));
inputs = repeat();
} else {
JOptionPane.showMessageDialog(null,
"Huh, I didn't get that, please say it again");
inputs = repeat();
}
} else {
inputs = repeat(); }
}
}
private String repeat() {
return JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
}
}
You code didn't work because:
you try to use static class Info, like a method - you declare inner static method with some class fields, and then just add code like in method, this is why it will not even compile. You can change it on static or nonstatic method, or add some methods to it. For example change static class Info on static void Info(){, and call it by just Info() (insted of Info info = new Info(); in main method.
you multiple times declare String inputs = JOptionPane.showInputDialog(null,"What do you want, Cookies, Milk or Both?");, it is enough to use just inputs = JOptionPane.showInputDialog(null,"What do you want, Cookies, Milk or Both?"); second time.
you mixed some brackets, like in:
while (true)
if(inputs.length() !=0) {
} // this is problematic bracket
so it will not work at all, and all nested if statments with it.
You need to fix it to at least run your application.
EDIT
It seems that you have a lot of unnecessary code, you can shorten it for example to:
import javax.swing.*;
public class Cookie {
public static void main(String[] args) {
while (true){
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
if(inputs.equalsIgnoreCase("cookies")) {
JOptionPane.showMessageDialog(null, "Here have some Cookies :)");
break;
}else if(inputs.equalsIgnoreCase("MILK")) {
JOptionPane.showMessageDialog(null, "Here is the Milk you wanted :)");
break;
}else if(inputs.equalsIgnoreCase("BOTH")) {
JOptionPane.showMessageDialog(null, "Here is your Cookies and Milk :)");
break;
}else{
JOptionPane.showMessageDialog(null, "Huh, I didn't get that, please say it again");
}
}
}
}
It seems like you want to get input from the user, and compare it to some preset strings (cookies, milk, and both)
What if you put the whole thing into a while(true) loop, and after getting the input from the user, you wrote something like
String message;
Boolean isValid = true;
if (inputs.equalsIgnoreCase("Cookies")){
message = "Have some cookies";
}
...
else{
message = "Try again";
isValid = false;
}
JOptionPane.showMessageDialog(null, message);
if(isValid) break;
Note: I'm writing this on a mobile, so syntax may not be exact. Use your discretion.

I am creating a login panel, but no matter the combination of user & pass the login won't be accepted

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCancel) {
System.exit(0);
}
if (e.getSource() == btnLogin) {
int i = 0;
while (loggedIn == false) {
if (i < TeacherData.length) {
if (txtUsername.getText() == TeacherData[i].getUsername() && String.valueOf(txtPassword.getPassword()) == TeacherData[i].getPassword()) {
loggedIn = true;
System.out.println("Login Successful");
}
else {
System.out.println("Invalid Username or Password.");
i++;
}
}
}
}
}
My login panel is coded to look like this http://imgur.com/TizgJeX.
Upon pressing the "login", the button the console prints out "Invalid Username or Password." 10 times (there are 10 teachers in teacherData).
Before anybody asks I have already made sure the getUsername() and getPassword() methods work. txtUsername is the name of the JTextField and txtPassword is the name of the JPasswordField. I do not receive any errors.
change this line:
if (txtUsername.getText() == TeacherData[i].getUsername() && String.valueOf(txtPassword.getPassword()) == TeacherData[i].getPassword()) {
to this
String password = String.valueOf(txtPassword.getPassword());
if (txtUsername.getText().equals(TeacherData[i].getUsername()) && password.equals(TeacherData[i].getPassword())){
with == you compare the object references and not the values.
As result of this you will never login successfully.
btw. the String.valueOf is not necessary.
getPassword returns a char[] array.
You have to convert it to String with: String.valueOf(txtPassword.getPassword())

InputDialog box showing a random "-1"

Everything runs perfectly but the String am1 = (String)JOptionPane.showInputDialog has a random default "-1" showing.
private void am1ActionPerformed(java.awt.event.ActionEvent evt) {
getinfo();//Set the random question and answer
am1.setEnabled(false);
Object[] options = {"Answer", "Cancel"};
int n = JOptionPane.showOptionDialog(null,
JeopardyGUI.question1_1,//Reference the question set
"",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
if(n == JOptionPane.YES_OPTION){
String am1 = (String)JOptionPane.showInputDialog("",JOptionPane.PLAIN_MESSAGE);
if(am1.equalsIgnoreCase(JeopardyGUI.answer1_1)){
Jscore += 100;
JOptionPane.showMessageDialog(null, JeopardyGUI.answer1_1 );
}
else if(!am1.equalsIgnoreCase(JeopardyGUI.answer1_1)){
Jscore += -100;
JOptionPane.showMessageDialog(null, JeopardyGUI.answer1_1 );
}
// else
// am1.setEnabled(true);
}
if(n == JOptionPane.NO_OPTION){
//am1.setVisible(false);
am1.setEnabled(true);
}
}
You are using:
public static String showInputDialog(Object message, Object initialSelectionValue)
JOptionPane.PLAIN_MESSAGE is your initialSelectionValue in this case. It's an int which is equal to -1 I'm guessing. What you actually want is probably:
JOptionPane.showInputDialog("Actual message", "");
Also, be careful:
String am1 = ...
Is hiding am1 the class member which is some Component it seems.
May I also suggest rewriting the handling logic as:
if(am1 != null && am1.equalsIgnoreCase(JeopardyGUI.answer1_1)){
Jscore += 100;
else Jscore += -100;
JOptionPane.showMessageDialog(null, JeopardyGUI.answer1_1 );
You need use the other static method, it don't receive a default value:
JOptionPane.showInputDialog("")
Check JOptionPane API here.

how to change default choice for JOptionPane.showOptionDialog to default_close_operation

i got this problem i used a JOptionPane in OptionDialog mode but i can't manage to set to default option that if i select the x in the upper right corner it closes itself; this is because in the declaration of the showOptionDialog it makes me selected only one of the Object[] array containing my choices this is the code
Object[] options = {"Vacanza","Cena","Prestazione","Bene"};
int choice = JOptionPane.showOptionDialog(frame,"Nuovo Prodotto","Scegli il prodotto",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[0]);
if (choice == 0) {
//things to do }
else if (choice == 1) {
//things to do }...
now i had to set the last parameter of the showoptiondialog as one of my choices resulting then if i select the X in the upper corner it anyway does the default choice when i just want it to close doing nothing, how can i fix this guys? pls help me
I tried this sample code to test what you are trying. When I click the X it prints out "Something else selected". Maybe I don't understand your question. Can you clarify?
import javax.swing.*;
public class Helloworld {
static JFrame frame;
public Helloworld(){
}
public void run(){
Object[] options = {"Vacanza","Cena","Prestazione","Bene"};
int choice = JOptionPane.showOptionDialog(
null,
"Nuovo Prodotto",
"Scegli il prodotto",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if(choice == 0){
System.out.println("0 selected");
}
else{
System.out.println("Something else selected");
}
}
public static void main(String[] args) {
Helloworld hw = new Helloworld();
hw.run();
}
}

Categories