user3303096
user3303096

Reputation: 21

Java- Can you get multiple variables using one JOptionPane message?

I am working on a project for homework and it is a simple lottery program. The program must ask for six numbers using JOptionPane and they must be less than 60. My question is could I get all six numbers using only ONE JOPtionPane input?

The program uses random number generators to compare the six input numbers to.

Upvotes: 2

Views: 3000

Answers (3)

Sarz
Sarz

Reputation: 1976

you can use this, and can adjust it accordingly

public class JOptionPaneMulti {
   public static void main(String[] args) {
      JTextField Field1 = new JTextField(5);
      JTextField Field2 = new JTextField(5);
      JTextField Field3 = new JTextField(5);
      JTextField Field4 = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.setLayout(new GridLayout(2,2));
      myPanel.add(new JLabel("input 1:"));
      myPanel.add(Field1);
      myPanel.add(new JLabel("input 2:"));
      myPanel.add(Field2);
      myPanel.add(new JLabel("input 3:"));
      myPanel.add(Field3);
      myPanel.add(new JLabel("input 4:"));
      myPanel.add(Field4);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("1 value: " + Field1.getText());
         System.out.println("2 value: " + Field2.getText());
         System.out.println("3 value: " + Field3.getText());
         System.out.println("4 value: " + Field4.getText());
      }

   }
}

Upvotes: 2

user330315
user330315

Reputation:

Yes this is possible. The message parameter to the various showXXX() methods is defined as Object. If you pass a Swing component as the "message" it will be displayed properly:

Something like:

JPanel panel = new JPanel();
JCheckBox cbx = JCheckBox("Option 1");
JTextField tf = new JTextField();
panel.add(cbx);
panel.add(tf);
... add more controls
int result = JOptionPane.showConfirmDialg(yourFrame, panel, "Dialog titel", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
   boolean doStuff = cbx.isSelected();
   String someValue = tv.getText();
   ... process other options here
}

Upvotes: 3

Paul Samsotha
Paul Samsotha

Reputation: 209102

JOptionPane.showInputDialog() returns a String, so you could split the return value.

String input = JOptionPane.showInputDialog(...);
String[] array = input.split("\\s+");

Check if the array length is six and also if they're all numbers. Put it in a while loop until both of those conditions are met. If not keep showing the dialog. If they are met then then do something with that input.

int num1 = Integer.parseInt(array[0]);
int num2 = Integer.parseInt(array[1]);
int num3 = Integer.parseInt(array[2]);
...

Upvotes: 1

Related Questions