如何在按钮组中选择该项目?

时间:2014-11-02 08:06:41

标签: java swing buttongroup

在Java swing中,我希望能够告诉按钮组中选择了哪个项目。我查看了Button Group API并没有看到任何可以实现此目的的东西。是否有一些方法可以让你发现这样做?

2 个答案:

答案 0 :(得分:1)

参考ButtonGroup: getSelection()

以下示例显示如何管理按钮组中项目的选择:

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;

public class MainClass {
  public static void main(String[] args) {
    JRadioButton dem = new JRadioButton("Bill", false);
    dem.setActionCommand("Bill");
    JRadioButton rep = new JRadioButton("Bob", false);
    rep.setActionCommand("Bob");
    JRadioButton ind = new JRadioButton("Ross", false);
    ind.setActionCommand("Ross");

    final ButtonGroup group = new ButtonGroup();
    group.add(dem);
    group.add(rep);
    group.add(ind);

    class VoteActionListener implements ActionListener {
      public void actionPerformed(ActionEvent ex) {
        String choice = group.getSelection().getActionCommand();
        System.out.println("ACTION Candidate Selected: " + choice);
      }
    }

    class VoteItemListener implements ItemListener {
      public void itemStateChanged(ItemEvent ex) {
        String item = ((AbstractButton) ex.getItemSelectable()).getActionCommand();
        boolean selected = (ex.getStateChange() == ItemEvent.SELECTED);
        System.out.println("ITEM Candidate Selected: " + selected + " Selection: " + item);
      }
    }

    ActionListener al = new VoteActionListener();
    dem.addActionListener(al);
    rep.addActionListener(al);
    ind.addActionListener(al);

    ItemListener il = new VoteItemListener();
    dem.addItemListener(il);
    rep.addItemListener(il);
    ind.addItemListener(il);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = frame.getContentPane();
    c.setLayout(new GridLayout(4, 1));
    c.add(new JLabel("Please Cast Your Vote"));
    c.add(dem);
    c.add(rep);
    c.add(ind);
    frame.pack();
    frame.setVisible(true);
  }
}

有关详细信息,请参阅Java教程How to Use the ButtonGroup Component

答案 1 :(得分:0)

  

我只需遍历你的JRadioButtons并调用isSelected()。如果你真的想从ButtonGroup出发,你只能进入模型。您可以将模型与按钮匹配,但如果您可以访问按钮,为什么不直接使用它们?

引自here

如果您最后使用了操作,那么为每个按钮设置操作也会有所帮助:

buttonGroup = new ButtonGroup();
...
...
button1.setActionCommand("Java");
...
buttonGroup.add(button1);
...

@Override
public void actionPerformed(ActionEvent e) {
    System.out.println("Selected Button: " + buttonGroup.getSelection().getActionCommand());
}