Is it possible to put multiple input in JOptionPane.showInputDialog? - java

I was wondering if it is possible to put multiple inputs in JOptionPane.showInputDialog and then get the user input and if the user has given a wrong input for one of the questions then provide them with a error, asking them to re-enter that specific data again.
For example, in the input I want questions like;
How many times have to been out? between 1-10.
Do you like number 1 or 2 or 3?
Please state for how many hours your have between 1-10 you have stop in a restaurant?
and I will need to add some more at a later stage.
So instead of have a JOptionPane.showInputDialog for each question like this:
int timeout;
do {
String timeoutinputbyuser = JOptionPane.showInputDialog("How many times have to been out? between 1-10.");
timeout = Integer.parseInt(timeoutinputbyuser);
} while (timeout < 1 || timeout > 10);
I want to have all the questions in one and provide a suitable error if the user gets any question wrong.

No, the input dialog only accepts a single input area.
Put the components in a JPanel and display it in a JOptionPane.showMessageDialog(..). Note that you can then have better components:
A JSpinner for selecting a number.
JRadioButton objects in a ButtonGroup for the choice of 3..

Try this
JTextField field1 = new JTextField();
JTextField field2 = new JTextField();
JTextField field3 = new JTextField();
JTextField field4 = new JTextField();
JTextField field5 = new JTextField();
Object[] message = {
"Input value 1:", field1,
"Input value 2:", field2,
"Input value 3:", field3,
"Input value 4:", field4,
"Input value 5:", field5,
};
int option = JOptionPane.showConfirmDialog(parent, message, "Enter all your values", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION)
{
String value1 = field1.getText();
String value2 = field2.getText();
String value3 = field3.getText();
String value4 = field4.getText();
String value5 = field5.getText();
}

Related

Convert String Array to int using JOptionPane

I'm doing a train ticket program. I want to convert certain text in the string array to a certain price using JOptionPane.
ex.
String[] option_1 = {"location1","location2", "location3","location4","location5"};
where location1 = $10, location2 = $23, etc.
all I know is I could use Interger.parseInt or double, but I don't know where to go next. Should I go with a loop or make a whole new array and make it equal to the string array. I'm wondering if there is a more easier method to execute this.
code :
public static void main (String [] args) {
String name;
String[] option_1 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
String[] option_2 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
name = JOptionPane.showInputDialog("Welcome to DME Ticketing System!\n\nEnter your name:");
String leave = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_1, option_1[0]);
String going = (String)JOptionPane.showInputDialog(null, "Leaving from",
"Train Station", JOptionPane.QUESTION_MESSAGE, null, option_2, option_2[0]);
// int pay = (Integer)JOptionPane.showInputDialog(null, "From: "+leave+"\nTo: "+going+"\nFare Price: "+"\n\nEnter your payment amount:",
// null, JOptionPane.PLAIN_MESSAGE, null, null,null);
// int op1 = Integer.parseInt(going);
// int op2 = Integer.parseInt(leave);
JOptionPane.showMessageDialog(null, "DME Ticketing System\nMalolos, Bulacan\n\n"
+ "Name: "+name
+"\nLocation: "+leave
+"\nDestination: "+going
+"\nFare: "
+"\nPayment: "//+pay
+"\nChange: "
, "RECEIPT",JOptionPane.INFORMATION_MESSAGE);
}
-The codes I turned into comments are giving me errors
showInputDialog always returns the input of the user as a String object, except from a variation where it returns the selected Object from the supplied ones. I am talking for Java version 8 for the sake of example.
Based on your question and comments, you basically want to:
Match String objects (their name) to integers (their value), so that you can calculate how much they will have to pay, plus the change afterwards.
Receive as input from the user the amount they will give, in order to calculate the change.
If so, then:
For the first case you can use some data structure(s) from which you will be able to match the locations with their value. For example a HashMap<String, Integer> can match the locations with their value, like so:
//Set up the origin options, along with their value:
HashMap<String, Integer> leavingOptions = new HashMap<>();
leavingOptions.put("North Avenue", 10);
leavingOptions.put("Quezon Avenue", 11);
leavingOptions.put("Kamuning", 12);
leavingOptions.put("Cubao", 13);
leavingOptions.put("Santolan", 14);
leavingOptions.put("Ortigas", 15);
leavingOptions.put("Shaw", 16);
leavingOptions.put("Boni", 17);
leavingOptions.put("Guadalupe", 18);
leavingOptions.put("Buendia", 19);
leavingOptions.put("Ayala", 20);
leavingOptions.put("Magallanes", 21);
leavingOptions.put("Taft", 22);
//Get user input for origin:
Object[] leavingOptionsArray = leavingOptions.keySet().toArray();
String leaving = (String) JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptionsArray, leavingOptionsArray[0]);
//Show output depending on user's input or cancel:
if (leaving != null)
JOptionPane.showMessageDialog(null, "You shall pay: " + leavingOptions.get(leaving));
else
JOptionPane.showMessageDialog(null, "Quiting...");
(note here that the casting of the returned value of the showInputDialog to a String reference is safe, just because the way we set up the options' array to contain only String objects)
Or you can use a String array with the locations along with an int array with the corresponding values, like so:
//Set up the origin options, along with their price:
String[] leavingOptions2 = new String[]{"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};
int[] price = new int[]{10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
//Get user input for origin:
Object leaving2 = JOptionPane.showInputDialog(null, "Leaving from:", "Train Station", JOptionPane.QUESTION_MESSAGE, null, leavingOptions2, leavingOptions2[0]);
//Show output depending on user's input or cancel:
if (leaving2 != null) {
//Find the price of the selected location:
int p = -1;
for (int i = 0; i < price.length; ++i)
if (leaving2.equals(leavingOptions2[i])) {
p = price[i];
break;
}
JOptionPane.showMessageDialog(null, "You shall pay: " + p);
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Or even better, you can use another object type other than String for the options array, for example a class named Location which will have the name and the price as properties, the toString method of which will return the name.
For the second part, obtain the user's input as a String from a JOptionPane and use Integer.parseInt(...) method on the user's input so as to be able to calculate the change afterwards, like so:
String paymentString = JOptionPane.showInputDialog(null, "Enter payment amount:", "Payment", JOptionPane.QUESTION_MESSAGE);
if (paymentString != null) {
try {
int payment = Integer.parseInt(paymentString);
JOptionPane.showMessageDialog(null, "You chose to pay: " + payment);
//Calculate change here...
}
catch (final NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "The input was invalid (not an 'int').");
}
}
else
JOptionPane.showMessageDialog(null, "Quiting...");
Remember that parseInt will throw a NumberFormatException (which is a RuntimeException) if its input String is not an int, so you will have to check for that using a try-catch block.

get values of Jtextfields when click OK in Dialog

My need is to display a tab in a JDialog (confirmDialog or inputDialog). The tab contains 2 JTextField per row. The display works fine :
but I don't know how to get the values of the JTextFields.
Here is the display code :
int size = model.getCheckedApplications().size();
// une ligne par application sélectionnée
layout = new GridLayout(size + 1, 3, 5, 5);
myPanel = new JPanel(layout);
myPanel.add(new JLabel("Application"));
myPanel.add(new JLabel("Version cadre"));
myPanel.add(new JLabel("Nouvelles natures"));
for (Application app : model.getCheckedApplications()) {
myPanel.add(new JLabel(app.getCode88()));
JTextField versionActuelleField = new JTextField(30);
versionActuelleField.setName("versionActuelle"
+ app.getCode88());
versionActuelleField.setText(app
.getVersionCadreActuelle());
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
myPanel.add(versionActuelleField);
myPanel.add(nouvellesNaturesField);
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then I don't know how to get the values when the user clicks on the OK Button :
if (result == 0) { // The user clicks on the ok button
You need to add them to some list that you store, so you can get at them again. Since you are adding them in reference to an application, I would suggest a Map
private Map<Application, JTextField> nouvellesNaturesFields = new ArrayListMultimap<Application, JTextField>(); //Or Hashmap, if the key is unique
private Map<Application, JTextField> versionActuelleFields = new ArrayListMultiMap<Application, JTextField>();
public List<JTextField> getNouvellesNaturesFields() {
return nouvellesNaturesFields ;
}
public List<JTextField> getVersionActuelleFields () {
return versionActuelleFields ;
}
//class code
for (Application app : model.getCheckedApplications()) {
//Other code
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
nouvellesNaturesFields.put(app, nouvellesNaturesField);
//Other code and same for your new nature fields
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then when the user clicks the confirm button, using the property accessor getNouvellesNaturesFields()or getVersionActuelleFields() you can iterate all the fields created, like so:
for (Map.Entry<Application, JTextField> entry: myMap.entries()) {
//Do something here
}
Or you could also get them via:
for (Application app : model.getCheckedApplications()) {
List<JTextField> data = myMap.get(app);
for(JTextField field : data) {
field.getText();
}
}
Since the key value probably won't be unique, I used an ArrayListMultiMap, but if it would be unique, then a HashMap should suffice
You assign the Jtextfield value to a string using the getText() method e.g below
String texfield = JTextField.getText();
Subsequently you use the String textfield wherever you want. And to get the right jtextfield you have to get text from the textfield you want for example you have four Jtexfield. Assuming they are JTextField1, JTextField2, JTextField3 and JTextField4. To get the value of JTextField3 you have
String texfield = JTextField3.getText();
The values should be in the JTextFields you created:
versionActuelleField
nouvellesNaturesField
Also, you might want to look at ParamDialog, which I implemented to be a generic solution to this question.
EDIT
Yes I see now that you are creating these JTextFields in a loop. So you need to create a Collection, I'd suggest a Map<String, JTextField> where you could map all of your application names to the matching JTextField, as well as iterate over the collection to get all application names / JTextFields.

how to stop execution if user forget to choose a jRadioButton in my code?

my problem may be simple but can't get idea to fix it ,i'm working on a project
and i put 2 radio Buttons to select gender ;
if user forget to determine gender how i can print error message to urge user
determine gender? the problem in the begining of this code :
private void jButton1ActionPerformed(ActionEvent evt) {
// TODO add your handling code here:
String radioText="";
if (jRadioButton1.isSelected()){radioText=jRadioButton1.getText();}
//male
if (jRadioButton2.isSelected()){radioText=jRadioButton2.getText();}
// female
/*** want here if nothing selected:
* JOptionPane.showMessageDialog(null,"you must determine gender!");
* and exit the code
*/
try
{
String first,second,last,operation;
int bMonth,bDay,bYear; // to set birthDay
int aMonth,aDay,aYear; //to set admissionDate
int fileNo,weight,height;
first = jTextField1.getText();
second = jTextField2.getText();
last = jTextField3.getText();
operation=jTextField14.getText();
bMonth = Integer.parseInt(jTextField4.getText());
bDay = Integer.parseInt(jTextField5.getText());
bYear = Integer.parseInt(jTextField6.getText());
aMonth =Integer.parseInt(jTextField7.getText());
aDay =Integer.parseInt(jTextField8.getText());
aYear = Integer.parseInt(jTextField9.getText());
fileNo=Integer.parseInt(jTextField10.getText());
weight=Integer.parseInt(jTextField12.getText());
height=Integer.parseInt(jTextField13.getText());
Date birth = new Date( bMonth, bDay, bYear );
Date admissionDate = new Date( aMonth, aDay,aYear );
Patient patient = new Patient( first, second,last,fileNo
,birth,admissionDate,weight,height,radioText,operation );
patientsArray.add(patient);
JOptionPane.showMessageDialog( null,patientsArray);
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null,"Input must be Integer!");
}
}
You should be using a ButtonGroup with the radio buttons. This will allow you to only select on radio button at a time. Then you can check the ButtonGroup for the selection.
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup group = new ButtonGroup();
group.add(male);
group.add(female);
Then in the ActionListener you can check the group:
if (group.getSelection() == null)
// no selection has been made
You will need to define the ButtonGroup as an instance variable so you can reference it in your ActionListener.
Read the section from the Swing tutorial on How to Use Radio Buttons for more information and example.

Returning object name with object values

Im really not sure as how to word this question. But im gonna try my best here. Bear with me if you could :)
I have a database with 3 tables (that i am dealing with right now). Fortunately they all have the same amount of columns. Im trying to input values into them using a "popup" form. (Not sure how to do that, but im using this link here as a guideline, and hoping it works)
Here is the code i have written for that method so far..
public form(int option, String val1, String val2, String val3, String val4, String val5)
{
val1 = null;
val2 = null;
val3 = null;
val4 = null;
val5 = null;
JTextField val1Field = new JTextField(20);
JTextField val2Field = new JTextField(20);
JTextField val3Field = new JTextField(20);
JTextField val4Field = new JTextField(20);
JTextField val5Field = new JTextField(20);
String name;
String lbl1 = null;
String lbl2 = null;
String lbl3 = null;
String lbl4 = null;
String lbl5 = null;
switch(option)
{
case 1: //if customer
name = "Customer Information";
lbl1 = "Customer No:";
lbl2 = "Customer Name:";
lbl3 = "Company Name:";
lbl4 = "Contact Number: ";
lbl5 = "Discount Rate:";
case 2: //if item
name = "Item Information";
lbl1 = "Item No:";
lbl2 = "Item Name:";
lbl3 = "Cost Price:";
lbl4 = "Selling Price: ";
lbl5 = "Stock:";
case 3: //if user
name = "Staff Information";
lbl1 = "Staff ID:";
lbl2 = "Full Name:";
lbl3 = "Username:";
lbl4 = "Password: ";
lbl5 = "adminusercheck:";
default:
JOptionPane.showMessageDialog(alphaPOS,
"Something went wrong! Try again!",
"ERROR",
JOptionPane.ERROR_MESSAGE);
}
JPanel formPanel = new JPanel();
formPanel.add(new JLabel(lbl1));
formPanel.add(val1Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl2));
formPanel.add(val2Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl3));
formPanel.add(val3Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl4));
formPanel.add(val4Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl5));
formPanel.add(val5Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
int result = JOptionPane.showConfirmDialog(null, formPanel,
name, JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
val1 = val1Field.getText();
val2 = val2Field.getText();
val3 = val3Field.getText();
val4 = val4Field.getText();
val5 = val5Field.getText();
}
return(option, val1, val2, val3, val4, val5);
}
Now.. it took me a while to realize that i cannot return values like that, and that i could instead return the object instead. I have a class made for each of these "tables" (Item, Customer and Staff).
But.. the thing is in the method above i need to use a switch so that i can have the labels made according to the type of Table.
So my question is, is there a way to pass the object and its name into the method? Or do i have it all wrong?
Any help is much appreciated.
It looks to me like you don't really need to return option since you never change it. Also, it looks like you were trying to have the caller pass variables into the method and let the method fill in the values of those variables. But Java doesn't have "output" or "reference" parameters the way C++ and PHP do, so this doesn't work. (You can pass in a reference to a mutable object and have a method set a field in that object, but you can't do that with String since it's immutable.)
If that's the case, then since the 5 things you want to return are all the same type, you could just make your method return a String[]:
public String[] form(int option)
{
String[] values = new String[] (5);
//values[0] = null; // not necessary since the array elements will already be null
//values[1] = null; ...
...
if (result == JOptionPane.OK_OPTION)
{
values[0] = val1Field.getText();
values[1] = val2Field.getText();
values[2] = val3Field.getText();
values[3] = val4Field.getText();
values[4] = val5Field.getText();
}
return values;
}
P.S. I recommend using arrays or ArrayList instead of separate variables like val1Field, val2Field, etc., so that you don't have to repeat code like this.
While there is a way to kind of do this, I would like to point out that this is not a good design! Don't generalize methods! I think that you need to try to redesign your code instead. If one of your classes changes, you will end up breaking them up anyway. Create a handler for each form type. You can do this using Factory pattern and then get the appropriate form, based on that. Might be a bit more work, but you will thank me later :)
If you need help on design, then that is something that we can definitely discuss.

Throwing a value to the other class

Can you help me with this?
Here is the code first:
public RegistrationForm(){
super("Registration Form (Assignment One)");
setLayout(new GridLayout(6,2));
l[0] = new JLabel("Name: ");
l[0].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[0]);
tf[0] = new JTextField();
tf[0].setToolTipText("Enter Your Full Name");
add(tf[0]);
l[1] = new JLabel("Age: ");
l[1].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[1]);
tf[1] = new JTextField();
tf[1].setToolTipText("Enter Your Age");
add(tf[1]);
l[2] = new JLabel("Birthday: ");
l[2].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[2]);
tf[2] = new JTextField();
tf[2].setToolTipText("Enter Your Birthday");
add(tf[2]);
l[3] = new JLabel("Address: ");
l[3].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[3]);
tf[3] = new JTextField();
tf[3].setToolTipText("Enter Your Address");
add(tf[3]);
l[4] = new JLabel("Contact Number: ");
l[4].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[4]);
tf[4] = new JTextField();
tf[4].setToolTipText("Enter Your Contact Number");
add(tf[4]);
b[0] = new JButton("Submit");
b[0].addActionListener(this);
add(b[0]);
b[1] = new JButton("Clear");
b[1].addActionListener(this);
add(b[1]);
}
So When I input a value to all and press "Submit" the previous class will close and another class will open and there it will show the value of the things I inputted from the previous class. . .
There is no default value to JTextfields, I'm going to enter the value myself.
How can i throw(I mean pass) a value to the other class?
Here is the code i have so far:
This is my method:
public String name(){
return tf[0].getText();
}
This is from my Other class:
public Form{
RegistrationForm form = new RegistrationForm();
JTextField name = form.name();
add(name);
}
You don't need to throw anything. Whatever class that displays this dialog will hold a reference to the instance of this class and can simply query the state of the fields once the dialog returns. This is much easier if the dialog window is a modal dialog such as a modal JDialog or a JOptionPane.
For instance, please look at my code in this example.
Edit
Also, this confuses me:
public Form{
RegistrationForm form = new RegistrationForm();
JTextField name = form.name();
add(name);
}
Does this code display the RegistrationForm object? Is RegistrationForm in fact a modal JDialog? It is very unusual to extract a JTextField from one GUI and add it to another, and I'm pretty sure that you don't want to do this. Again, what you want to do is:
Display your RegistrationForm as a modal JDialog.
After it returns, call getter methods on the RegistrationForm object that extracts the Strings held by the text fields of the object.
For more details, you'll still need to tell us a lot more about your code and your problem.

Categories

Resources