0

Well its weird. I am not good with radiobuttons by the way. But I made a JPanel program in netbeans which includes a RadioButton. You enter all this information with JTextFields(no problem) and then lastly I had a JButton which you click the choice you want. Then I have a JButton that takes all the information and outputs this. For the RadioButton, I first entered the usual:

    family = new JRadioButton("Family", true);
    friend = new JRadioButton("Friend");
    relative = new JRadioButton("Relative");
    friendFriend = new JRadioButton("Friend of Friend");

    ButtonGroup group = new ButtonGroup();
    group.add (friend);
    group.add (family);
    group.add (relative);
    group.add (friendFriend);

(I'm not sure if I needed a listner for the RadioButtons or not but my program still seems to "crash" no matter what).

then I had one action listner for the JButton which included all the textfields and radio buttons. But the RadioButton is the issue.

In the action listner I had: Object source = event.getSource();

        if (source == family)
            relation1 = true;
        else
            if (source == friend)
                relation2 = true;
            else
                if(source == relative)
                    relation3 = true;
                else
                    if(source == friendFriend)
                    relation4 = true;

Then I made a relation class: public class Relation { private boolean arrayFamily, arrayFriend, arrayRelative, arrayFriendFriend;

public Relation(boolean relation1, boolean relation2, boolean relation3,
        boolean relation4)
{
    this.arrayFamily = relation1;
    this.arrayFriend = relation2;
    this.arrayRelative = relation3;
    this.arrayFriendFriend = relation4;
}

public String relations ()
{
    String relationship = null;

    if(arrayFamily && !arrayFriend && !arrayRelative && !arrayFriendFriend == true)
    {
        relationship = "Family";
    }
    else
        if(arrayFriend && !arrayFamily && !arrayRelative && 
                !arrayFriendFriend == true)
        {
            relationship = "Friend";
        }
        else
            if(arrayRelative && !arrayFamily && !arrayFriend && 
                    !arrayFriendFriend == true)
            {
                relationship = "Relative";
            }
            else
                if(arrayFriendFriend && !arrayFamily && !arrayFriend &&
                        !arrayRelative == true)
                {
                    relationship = "Friend of a Friend";
                }
    return relationship;
}

}

LASTLY back in the action listner, I implementer this class:

        Relation relationship = new Relation(relation1, relation2, relation3
                , relation4);

        String arrayRelation = relationship.relations();

I lastly included arrayRelation in an array but the array worked fine.

My problem is that the output of the array for my RadioButtons keeps reading "null" (most likey because this code: String relationship = null;). I assume this means that none of my if else statements were satisfied and I really dont know why. Also important to point out is that if I click submit without clicking any radio button (the button stays on "family"), it reads null. If I click a button once it works perfectly reading the string I intended. But if I click another button afterwards and click submit again, the string goes back to "null".

I know its lengthy but I would really appreciate any help because I am lost.

P.S. some parts of my code are repetitive because I was playing around trying to fix the problem.

mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

1

I suggest you handle your action events separately, for example:

family.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            familyActionPerformed(evt);
        }
    });

Then implement familyActionPerformed(evt):

private void familyActionPerformed(java.awt.event.ActionEvent evt) {
    // every click on family radio button causes the code here to be executed
    relation1 = true;
}

Also write an event handler for the button you click, like this:

submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // Here test the state of each radio button
    relation1 = family.isSelected();
    relation2 = friend.isSelected();
    relation3 = relative.isSelected();
    relation4 = friendFriend.isSelected();
}

MORE EDIT: Doing what you're doing with NetBeans should be very easy. Here are tutorials that will clear it all up for you:

  1. Tutorial 1

  2. Tutorial 2


I explain the solution again:

Using 'family' button as an example, in your constructor where you have created and initialised your GUI components do this:

JRadioButton family = new JRadioButton();
// do any other thing you want to do to this button and finally..
family.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            familyActionPerformed(evt);
        }
    });

JButton submit = new JButton("Submit");
submit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            submitActionPerformed(evt);
        }
    });

Then somewhere create these methods:

private void familyActionPerformed(java.awt.event.ActionEvent evt){
    // each time family is selected, you code processes the lines below:
    ...
}

private void submiteActionPerformed(java.awt.event.ActionEvent evt){
    relation1 = family.isSelected();
    relation2 = friend.isSelected();
    relation3 = relative.isSelected();
    relation4 = friendFriend.isSelected();
}

Do something similar for the rest of the RadioButtons.

Igwe Kalu
  • 14,286
  • 2
  • 29
  • 39
  • I have a feeling it has something to do with my relation class because the problem is that it outputs "null" instead of the strings. Your suggestion didn't change anything and if I didn't click on any RadioButton (just clicked submit), it gave me this error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JRadioButton – user1888854 Dec 09 '12 at 04:07
  • I just scanned through your question quickly, forgive me if I didn't understand it. Well look at the edit I added, it's the best way to solve the problem. – Igwe Kalu Dec 09 '12 at 04:12
  • @user1888854: I strongly believe that you're better off using the ButtonGroup object since it holds a reference to the selected JRadioButton's model, if one has been selected. – Hovercraft Full Of Eels Dec 09 '12 at 04:17
  • @HovercraftFullOfEels, that's just one way of doing it, it's not necessarily better. Writing handlers for actions performed on components separately makes the code easier to read, and it's easier to debug. Plus you can easily add additional logic for when the action takes place. – Igwe Kalu Dec 09 '12 at 04:21
  • @user1888854 simply double-click on a component on the form design, and NetBeans will generate the stub for the component's action method. And all you have to do is just plugin the specific code to be executed when an action takes place. I hope you'll find these suggestions helpful - cos I only just skimmed through your question. But I offered a tested and trusted method for dealing with this kind of scenario. – Igwe Kalu Dec 09 '12 at 04:26
  • The problem with your method is, if you later add another JRadioButton, then you have to update all methods that rely on this kind of code. The advantage to using the ButtonGroup is that the ButtonGroup takes care of this for you. So your solution does not scale well and is prone to propagation of bugs. – Hovercraft Full Of Eels Dec 09 '12 at 04:35
  • no, if you later add another JRadioButton, all you have to do is add an accompanying method to process its button click action. Think of the methods as modules which are decoupled or loosely-coupled. I believe you get a much more bug-free code that way. Following your suggestion, you have to go back to the action method of the ButtonGroup and fix in some logic in between existing code to accomodate the addition of the new button. After all you don't add a new button without addressing the function it represents. – Igwe Kalu Dec 09 '12 at 04:43
  • @IGwe: I dont understand how how you created the action listner with familyActionPerformed(evt). Sorry I am new to programming so I only really know the basics. I don't understand how to implement what you said in family.addActionListner...etc. of what you said into actual netbeans code. – user1888854 Dec 09 '12 at 04:45
  • No, it's the exact opposite. With my code all you would need to do would be to add one more String to the Array. nothing more. – Hovercraft Full Of Eels Dec 09 '12 at 04:46
  • Or if anyone knows what I did wrong with my boolean to RadioButton relation that would be great too. The code has that extra class because I needed to create 5 classes for the entire programming project. But I am not sure what I did wrong in my relation class, or possibly in the action listner where I wanted only 1 (the submit button). – user1888854 Dec 09 '12 at 04:46
  • @user1888854 simply DOUBLE-CLICK on the 'family' button, NetBeans will create the actionListener and add it to the component. Meanwhile, it will also generate the familyActionPerformed(evt) {// just add something here} method which is the only thing you get to edit. – Igwe Kalu Dec 09 '12 at 04:49
  • Aren't you using NetBeans's GUI builder? Here are tutorials on how to use them: first: http://netbeans.org/kb/docs/java/gui-functionality.html second: http://netbeans.org/kb/docs/java/quickstart-gui.html – Igwe Kalu Dec 09 '12 at 04:51
  • @IGwe: Thats why I was confused. No I am not using the GUI builder. I just started a beginner course and we never learned about it, so I chose to do it all manually (can't change this now). Sorry for the confusion I know most everyone uses the GUI builder since it is much easier. – user1888854 Dec 09 '12 at 04:55
  • @user1888854: not true. If you use the GUI builder at an early stage, it will shield you from having to understand the under-pinnings of the Swing library, and this will make it more difficult to create anything but the most basic GUI's. You're far better off at this stage using the tutorials and creating your GUI's by hand. – Hovercraft Full Of Eels Dec 09 '12 at 04:59
  • @HovercraftFullOfEels: That makes sense. I'm just confused and frustrated because the rest of my program worked except these RadioButtons that keep outputting "null". I created another class on purpose so I was hoping their was a way to make it work. – user1888854 Dec 09 '12 at 05:02
  • @user1888854: For your code to work, in your actionPerformed you would have to first set all booleans to false before you set the desired one to true, but your code is very fragile and bug prone and not a clean way to solve your problem. You're better off with either IGwe's or my solution. – Hovercraft Full Of Eels Dec 09 '12 at 05:09
  • @user1888854 I have edited my answer. It should be very clear now. But I suggest you take a break - drink soda or something else, and forget about the problem for 5 minutes or so. When come back calmer and more composed you'll figure it all out. – Igwe Kalu Dec 09 '12 at 05:16
  • I really appreciate the help from both of you. You are both very knowledgeable and helped me out a lot. Finally got it to work after some rest haha. – user1888854 Dec 09 '12 at 18:17
1

I think that you're making things way too complex for yourself. If all you want is the String of the JRadioButton pressed, then use the ButtonGroup to get it for you. It can return the ButtonModel of the selected JRadioButton (if any one was selected), and from that you can extract the actionCommand String, although you'll have to remember to set this when you create your JRadioButton.

For example:

import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class JRadioExample extends JPanel {
   private static final String[] RADIO_TITLES = { "Family", "Friend",
         "Relative", "Friend or Relative" };
   private ButtonGroup btnGrp = new ButtonGroup();

   public JRadioExample() {
      for (int i = 0; i < RADIO_TITLES.length; i++) {
         JRadioButton rBtn = new JRadioButton(RADIO_TITLES[i]);
         rBtn.setActionCommand(RADIO_TITLES[i]); // ***** this is what needs to
                                                 // be set
         btnGrp.add(rBtn);
         add(rBtn);
      }

      add(new JButton(new BtnAction("Get Chosen Selection")));
   }

   private class BtnAction extends AbstractAction {

      public BtnAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         ButtonModel model = btnGrp.getSelection();
         if (model != null) {
            String actionCommand = model.getActionCommand();
            System.out.println("Selected Button: " + actionCommand);
         } else {
            System.out.println("No Button Selected");
         }    
      }
   }

   private static void createAndShowGui() {
      JRadioExample mainPanel = new JRadioExample();

      JFrame frame = new JFrame("JRadioExample");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373