【问题标题】:Trouble with RadioButtons and booleans connectionRadioButtons 和布尔连接的问题
【发布时间】:2012-11-26 21:27:15
【问题描述】:

嗯,这很奇怪。顺便说一句,我不擅长单选按钮。但是我在 netbeans 中制作了一个 JPanel 程序,其中包括一个 RadioButton。您使用 JTextFields 输入所有这些信息(没问题),最后我有一个 JButton,您可以单击所需的选择。然后我有一个 JButton,它获取所有信息并输出它。对于 RadioButton,我首先输入的是通常的:

    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);

(我不确定我是否需要 RadioButtons 的侦听器,但无论如何我的程序似乎仍然“崩溃”)。

然后我有一个用于 JButton 的操作侦听器,其中包括所有文本字段和单选按钮。但是 RadioButton 是问题所在。

在我的动作监听器中: 对象来源 = 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;

然后我做了一个关系类: 公共类关系{ 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;
}

}

最后回到动作监听器,我实现了这个类:

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

        String arrayRelation = relationship.relations();

我最后将 arrayRelation 包含在一个数组中,但该数组工作正常。

我的问题是我的 RadioButtons 的数组输出一直显示为“null”(最有可能是因为此代码:String relationship = null;)。我认为这意味着我的 if else 语句都不满足,我真的不知道为什么。 同样重要的是要指出,如果我单击提交而不单击任何单选按钮(按钮保持在“家庭”上),它会显示为空。如果我单击一个按钮,它可以完美地读取我想要的字符串。但是如果我之后单击另一个按钮并再次单击提交,则字符串将返回“null”。

我知道它很长,但我真的很感激任何帮助,因为我迷路了。

附:我的代码的某些部分是重复的,因为我一直在尝试解决问题。

【问题讨论】:

  • 在您更了解 Swing 之前最好不要使用 NetBeans 的代码生成工具,否则它会妨碍您学习 Swing。

标签: java swing if-statement boolean jradiobutton


【解决方案1】:

我建议你单独处理你的action事件,例如:

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

然后实现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;
}

还为您单击的按钮编写一个事件处理程序,如下所示:

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();
}

更多编辑: 使用 NetBeans 执行您正在执行的操作应该非常容易。以下教程将为您解决所有问题:

  1. Tutorial 1

  2. Tutorial 2


我再解释一下解决办法:

以“family”按钮为例,在您创建和初始化 GUI 组件的构造函数中执行以下操作:

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);
        }
    });

然后在某处创建这些方法:

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();
}

对其他 RadioButtons 执行类似操作。

【讨论】:

  • 我感觉它与我的关系类有关,因为问题是它输出“null”而不是字符串。你的建议没有改变任何东西,如果我没有点击任何 RadioButton(只是点击提交),它给了我这个错误:线程“AWT-EventQueue-0”中的异常 java.lang.ClassCastException: javax.swing.JButton无法转换为 javax.swing.JRadioButton
  • 我只是快速浏览了您的问题,如果我不明白,请原谅。好吧,看看我添加的编辑,这是解决问题的最佳方法。
  • @user1888854:我坚信最好使用 ButtonGroup 对象,因为它包含对选定 JRadioButton 模型的引用(如果已选择一个)。
  • @HovercraftFullOfEels,这只是一种方法,不一定更好。分别为在组件上执行的操作编写处理程序使代码更易于阅读,并且更易于调试。此外,您还可以轻松地为动作发生时间添加额外的逻辑。
  • @user1888854 只需在表单设计上双击一个组件,NetBeans 就会为该组件的操作方法生成存根。而你所要做的只是插入一个动作发生时要执行的特定代码。我希望您会发现这些建议对您有所帮助 - 因为我只是浏览了您的问题。但我提供了一种经过测试且值得信赖的方法来处理这种情况。
【解决方案2】:

我认为你把事情弄得太复杂了。如果您想要的只是按下的 JRadioButton 的字符串,则使用 ButtonGroup 为您获取它。它可以返回所选 JRadioButton 的 ButtonModel(如果选择了任何一个),然后您可以从中提取 actionCommand 字符串,尽管您必须记住在创建 JRadioButton 时设置它。

例如:

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();
         }
      });
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-14
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多