2

I am having problem to return a simple int value out of radiobutton i have created.

        static int f5(String question) 
        {
            int intValue = 0;
            answered = false;
            JFrame f = new JFrame(question);
            f.setSize(300, 750);

            f.addWindowListener(new WindowAdapter() 
            {
              public void windowClosing(WindowEvent we) 
              { 
                  System.exit(0); 
              }
            });

            JPanel p = new JPanel(new GridLayout(0,1,3,3));
            final ButtonGroup bg = new ButtonGroup();
            JRadioButton radioButton;

            p.add(radioButton = new JRadioButton("q1"));
            radioButton.setActionCommand("1");
            bg.add(radioButton);
            p.add(radioButton = new JRadioButton("q2"));
            radioButton.setActionCommand("2");
            bg.add(radioButton);
            p.add(radioButton = new JRadioButton("q3"));
            radioButton.setActionCommand("3");
            bg.add(radioButton);
            p.add(radioButton = new JRadioButton("q4"));
            radioButton.setActionCommand("4");
            bg.add(radioButton);

            JButton orderButton = new JButton("Submit");
            p.add(orderButton);

            f.getContentPane().setLayout(new FlowLayout());
            f.getContentPane().add(p);
            f.pack();


            orderButton.addActionListener(new ActionListener() 
            {
              public void actionPerformed(ActionEvent ae) 
              {

                String ans = bg.getSelection().getActionCommand();
                boolean sel;
                f5Answer = Integer.parseInt(ans);
                answered = true;
                System.out.println("in void: " + f5Answer); //how to return the f5Answer?

              }

            });
            f.setVisible(true);


            f5Answer = intValue;
            System.out.println("out of void: " + f5Answer);//this only returns 0 right away



            return intValue;
        }

I would like to return the value and end function after I find value when i press submit. Right now, the value is returned to 0 right after I use the function in main. How can I make the function to only return the value after submit is pressed??

Thanks in advance!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Joe Park
  • 139
  • 3
  • 12
  • did you by any chance forget the homework tag :-) – kleopatra Mar 21 '12 at 14:28
  • You do it in the ActionListener -- but you already have code that does this! So I'm confused -- what exactly *is* your problem? – Hovercraft Full Of Eels Mar 21 '12 at 14:29
  • haha it is not homework! The problem is, I need to return this value. I used actionlistener but that is in void. I cant return values in void. Basically, in the function, I select radiobutton and it should return the appropriate value. If i select q3, it should return int 3. – Joe Park Mar 21 '12 at 14:31

1 Answers1

5

I think I sort of understand your problem. What you should do is make your ButtonGroup object a private class field, and then give your class a public method, say something like ...

public int getSelection() {
   ButtonModel btnModel = bg.getSelection();
   if (bg == null) {
     // TODO: throw an exception -- no radio button has been selected
   } else {
      return Integer.parseInt(btnModel.getActionCommand());
   }
}

Then in your submit button's actionlistener, notify any and all parties that the selection has been made, and that they should call the getSelection() method on this object to find out what the selection is.

Edit
Ah, now I see what you're trying to do -- you're trying to create a question dialog. My suggestion is that you in fact do just this, create a dialog not a JFrame, and in fact make it a modal dialog so that your method will wait for the user to respond before moving on, and so that when the method ends, the ButtonGroup will in fact hold the correct information. The easiest way to do this is to use a JOptionPane which are very flexible critters, and use one that holds a JPanel that holds a grid of your JRadioButtons. Then find out what the user selected after the JOptionPane returns. Here, a static method could work fine since you're not changing the state of an object. For example:

   public static String myQuestion(String question, String[] answers) {
      JPanel panel = new JPanel(new GridLayout(0, 1));
      final ButtonGroup btnGroup = new ButtonGroup();

      for (String answer : answers) {
         JRadioButton radioBtn = new JRadioButton(answer);
         radioBtn.setActionCommand(answer);
         btnGroup.add(radioBtn);
         panel.add(radioBtn);
      }

      String[] options = { "Submit", "Cancel" };
      String initialValue = "Submit";

      int optionResult = JOptionPane.showOptionDialog(null, panel, question,
            JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
            options, initialValue);

      // *** code will pause here and wait for the user to handle the modal dialog

      if (optionResult != 0) {
         return ""; // did not select "Submit"
      } else if (optionResult == 0) {
         ButtonModel btnModel = btnGroup.getSelection();
         if (btnModel == null) {
            return ""; // error! nothing selected
         } else {
            return btnModel.getActionCommand();
         }
      }
      return "";
   }

   public static void main(String[] args) {
      String question = "Where is Ulysses S. Grant buried?";
      String[] answers = { "In my back yard", "At the white house",
            "red my lord! No, blue!", "In Grant's tomb", "Who the hell is Ulysses S. Grant?" };
      String selectedString = myQuestion(question, answers);
      System.out.println("Answer selected: " + selectedString);
   }
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Hmm does this mean I need to created whole new class called ButtonGroup? Is there way I can just add getSelection function into existing ButtonGroup? – Joe Park Mar 21 '12 at 14:37
  • Thank you!! you read my mind. I did end up doing other way using while loop until user clicks a submit button. However it seems like this way will work out much better! Thank you again! – Joe Park Mar 21 '12 at 15:26
  • @JoePark: polling in a while loop in this way is *very* dangerous and can often freeze the Swing event thread. I strongly urge you not to do this but instead to use a modal dialog as my example above shows. This way there is no danger of stepping on the Swing event thread and causing your application to become unresponsive. – Hovercraft Full Of Eels Mar 21 '12 at 15:47