如何获取JRadioButton的文本值

发布于 2024-12-17 14:51:36 字数 583 浏览 2 评论 0原文

我正在用java创建一个项目。我的程序有 80 个 JRadioButtons ....我需要获取它们的文本值..现在这些单选按钮已添加到 ButtonGroup(每个单选按钮有 4 个单选按钮)...

我知道如何从单选按钮获取文本值下面的代码

radiobutton1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String q1=e.getActionCommand();
                JOptionPane.showMessageDialog(null, q1);
            }
        });

现在有什么简单的方法可以做到这一点吗?因为我必须执行上面的代码 80 次(对于 80 个单选按钮,如果我使用上面的方法,请使用上面的方法

附加信息 - 我总共有 20 个 ButtonGroups,每个 ButtonGroups 有 4 个单选按钮。所以(80 个单选按钮)。

I am creating a project in java. My Program has 80 JRadioButtons .... I need the get the text value of them.. Now these radiobuttons are added to ButtonGroup(each has 4 radio buttons)...

I know how to get the text value from the radio button by this following code

radiobutton1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String q1=e.getActionCommand();
                JOptionPane.showMessageDialog(null, q1);
            }
        });

Now is there any easy way to do this? because i will have to do this above code for 80 times(for eighty radiobuttons if i use the above use the above method

Additional Info- I have Total 20 ButtonGroups each with 4 radio buttons. So(80 radio buttons).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

凑诗 2024-12-24 14:51:36
I have Total 20 ButtonGroups each with 4 radio buttons. So(80 radio buttons).

那么最简单的方法是

String actionCommand = "";
ButtonModel buttonModel = myButtonGroup.getSelection();
if (buttonModel != null) {
   actionCommand = buttonModel.getActionCommand();
} else {
   // buttonModel is null.
   // this occurs if none of the radio buttons 
   // watched by the ButtonGroup have been selected.
}
I have Total 20 ButtonGroups each with 4 radio buttons. So(80 radio buttons).

then easiest way is

String actionCommand = "";
ButtonModel buttonModel = myButtonGroup.getSelection();
if (buttonModel != null) {
   actionCommand = buttonModel.getActionCommand();
} else {
   // buttonModel is null.
   // this occurs if none of the radio buttons 
   // watched by the ButtonGroup have been selected.
}
尘世孤行 2024-12-24 14:51:36

我猜你面临这个问题的原因是因为你手动创建了每个 JRadioButton (而不是循环)。

如果你确实不能这样做,你可以使用一些智能代码:

Container c = ...; // The component containing the radiobuttons
Component[] comps = c.getComponents();
for (int i = 0; i < c.getComponentCount(); ++i)
{
    Component comp = comps[i];
    if (comp instanceof JRadioButton)
    {
         JRadioButton radiobutton = (JRadioButton) comp;
         // add the listener
         radio.addActionListener(...);
    }
}

The reason you are facing this problem is because you created every JRadioButton manually, I guess (instead of a loop).

If you really can't do it otherwise, you can use some intelligent code:

Container c = ...; // The component containing the radiobuttons
Component[] comps = c.getComponents();
for (int i = 0; i < c.getComponentCount(); ++i)
{
    Component comp = comps[i];
    if (comp instanceof JRadioButton)
    {
         JRadioButton radiobutton = (JRadioButton) comp;
         // add the listener
         radio.addActionListener(...);
    }
}
橙味迷妹 2024-12-24 14:51:36

您可能不应该为每个单选按钮单独定义操作侦听器,而应该为所有单选按钮定义一个公共操作侦听器。

例如

public class RadioActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        //String q1=e.getActionCommand();

        //Use the ActionEvent#getSource() method which gives you the reference to the
        //radio-button that caused the event
        JRadioButton theJRB = (JRadioButton) e.getSource();
        JOptionPane.showMessageDialog(null, theJRB.getText());
    }
}

然后,您可以按如下方式使用它:

ActionListener radioAL = new RadioActionListener();

radiobutton1.addActionListener(radioAL);
radiobutton2.addActionListener(radioAL);

另外, ActionEvent#getActionCommand() 返回与操作关联的命令字符串,而不是完全命令组件的文本。

May be instead of defining action-listener for each radio-button individually, you should define a common action-listener for all the radio-buttons.

e.g.

public class RadioActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        //String q1=e.getActionCommand();

        //Use the ActionEvent#getSource() method which gives you the reference to the
        //radio-button that caused the event
        JRadioButton theJRB = (JRadioButton) e.getSource();
        JOptionPane.showMessageDialog(null, theJRB.getText());
    }
}

Then, you can use it as follows:

ActionListener radioAL = new RadioActionListener();

radiobutton1.addActionListener(radioAL);
radiobutton2.addActionListener(radioAL);

Also, the ActionEvent#getActionCommand() returns the command string associated with the action not extacly the text of command-component.

拥抱没勇气 2024-12-24 14:51:36

实现您想要的设计的关键(我认为)是充分利用数组的力量。例如,您可以有一个保存 JRadioButton 文本的二维字符串数组和一个 ButtonGroups 的一维数组,然后能够轻松设置 GUI 并使用 for 循环和嵌套 for 循环查询 GUI(以及使用 mKorbel 的出色建议)。

例如:

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

public class Foo002 extends JPanel {
   public static final String[][] RADIO_TEXTS = {
      {"A1","A2","A3","A4"}, {"B1","B2","B3","B4"}, 
      {"C1","C2","C3","C4"}, {"D1","D2","D3","D4"}, 
      {"E1","E2","E3","E4"}, {"F1","F2","F3","F4"}, 
      {"G1","G2","G3","G4"}, {"H1","H2","H3","H4"}, 
      {"I1","I2","I3","I4"}, {"J1","J2","J3","J4"}, 
      {"K1","K2","K3","K4"}, {"L1","L2","L3","L4"}, 
      {"M1","M2","M3","M4"}, {"N1","N2","N3","N4"}, 
      {"O1","O2","O3","O4"}, {"P1","P2","P3","P4"}, 
      {"Q1","Q2","Q3","Q4"}, {"R1","R2","R3","R4"}, 
      {"S1","S2","S3","S4"}, {"T1","T2","T3","T4"}
      };

   private ButtonGroup[] btnGroups = new ButtonGroup[RADIO_TEXTS.length];

   public Foo002() {
      JPanel radioPanel = new JPanel(new GridLayout(0, 2));
      for (int i = 0; i < RADIO_TEXTS.length; i++) {
         JPanel panel = new JPanel(new GridLayout(1, 0));
         btnGroups[i] = new ButtonGroup();
         for (int j = 0; j < RADIO_TEXTS[i].length; j++) {
            String text = RADIO_TEXTS[i][j];
            JRadioButton rBtn = new JRadioButton(text);
            rBtn.setActionCommand(text);
            btnGroups[i].add(rBtn);
            panel.add(rBtn);
         }
         panel.setBorder(BorderFactory.createLineBorder(Color.black));
         radioPanel.add(panel);
      }

      JButton getRadioChoicesBtn = new JButton(new AbstractAction("Get Radio Choices") {
         public void actionPerformed(ActionEvent arg0) {
            for (ButtonGroup btnGroup : btnGroups) {
               ButtonModel btnModel = btnGroup.getSelection();
               if (btnModel != null) {
                  System.out.println("Selected Button: " + btnModel.getActionCommand());
               }
            }
         }
      });
      JPanel btnPanel = new JPanel();
      btnPanel.add(getRadioChoicesBtn);

      setLayout(new BorderLayout());
      add(radioPanel, BorderLayout.CENTER);
      add(btnPanel, BorderLayout.SOUTH);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("RadioPanels");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new Foo002());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

The key to implementing a design like you desire (I think) is to use arrays to their fullest power. For instance, you could have a 2-Dimensional array of String that holds the JRadioButton texts, and a 1-Dimensional array of ButtonGroups and then be able to easily set up your GUI and query your GUI with for loops and nested for loops (and using the excellent suggestion of mKorbel).

For example:

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

public class Foo002 extends JPanel {
   public static final String[][] RADIO_TEXTS = {
      {"A1","A2","A3","A4"}, {"B1","B2","B3","B4"}, 
      {"C1","C2","C3","C4"}, {"D1","D2","D3","D4"}, 
      {"E1","E2","E3","E4"}, {"F1","F2","F3","F4"}, 
      {"G1","G2","G3","G4"}, {"H1","H2","H3","H4"}, 
      {"I1","I2","I3","I4"}, {"J1","J2","J3","J4"}, 
      {"K1","K2","K3","K4"}, {"L1","L2","L3","L4"}, 
      {"M1","M2","M3","M4"}, {"N1","N2","N3","N4"}, 
      {"O1","O2","O3","O4"}, {"P1","P2","P3","P4"}, 
      {"Q1","Q2","Q3","Q4"}, {"R1","R2","R3","R4"}, 
      {"S1","S2","S3","S4"}, {"T1","T2","T3","T4"}
      };

   private ButtonGroup[] btnGroups = new ButtonGroup[RADIO_TEXTS.length];

   public Foo002() {
      JPanel radioPanel = new JPanel(new GridLayout(0, 2));
      for (int i = 0; i < RADIO_TEXTS.length; i++) {
         JPanel panel = new JPanel(new GridLayout(1, 0));
         btnGroups[i] = new ButtonGroup();
         for (int j = 0; j < RADIO_TEXTS[i].length; j++) {
            String text = RADIO_TEXTS[i][j];
            JRadioButton rBtn = new JRadioButton(text);
            rBtn.setActionCommand(text);
            btnGroups[i].add(rBtn);
            panel.add(rBtn);
         }
         panel.setBorder(BorderFactory.createLineBorder(Color.black));
         radioPanel.add(panel);
      }

      JButton getRadioChoicesBtn = new JButton(new AbstractAction("Get Radio Choices") {
         public void actionPerformed(ActionEvent arg0) {
            for (ButtonGroup btnGroup : btnGroups) {
               ButtonModel btnModel = btnGroup.getSelection();
               if (btnModel != null) {
                  System.out.println("Selected Button: " + btnModel.getActionCommand());
               }
            }
         }
      });
      JPanel btnPanel = new JPanel();
      btnPanel.add(getRadioChoicesBtn);

      setLayout(new BorderLayout());
      add(radioPanel, BorderLayout.CENTER);
      add(btnPanel, BorderLayout.SOUTH);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("RadioPanels");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new Foo002());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}
我偏爱纯白色 2024-12-24 14:51:36

这对我有用

   {
   ...
   String nomSelected = getSelectedButtonText(jbgVariables);
   ...
   }

   String getSelectedButtonText(ButtonGroup buttonGroup) {
       Enumeration<AbstractButton> enu = buttonGroup.getElements();
       while (enu.hasMoreElements()) {
          AbstractButton button = enu.nextElement();
          if(button.isSelected())
              return button.getText();
    
    }

    return null;
  }

This works for me

   {
   ...
   String nomSelected = getSelectedButtonText(jbgVariables);
   ...
   }

   String getSelectedButtonText(ButtonGroup buttonGroup) {
       Enumeration<AbstractButton> enu = buttonGroup.getElements();
       while (enu.hasMoreElements()) {
          AbstractButton button = enu.nextElement();
          if(button.isSelected())
              return button.getText();
    
    }

    return null;
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文