gpt4 book ai didi

java - 如何找到按钮组中的该项被选中?

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:45 24 4
gpt4 key购买 nike

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

最佳答案

引用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了解更多信息。

关于java - 如何找到按钮组中的该项被选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26697266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com