[英]How do I get which JRadioButton is selected from a ButtonGroup
我有一個包含表單上的單選按鈕的 Swing 應用程序。 我有ButtonGroup
,但是,查看可用的方法,我似乎無法獲得所選JRadioButton
的名稱。 到目前為止,這是我能說的:
從 ButtonGroup 中,我可以執行getSelection()
來返回ButtonModel
。 從那里,我可以執行getActionCommand
,但這似乎並不總是有效。 我嘗試了不同的測試並得到了不可預測的結果。
同樣從ButtonGroup
,我可以從getElements()
獲得一個枚舉。 但是,我將不得不遍歷每個按鈕以檢查它是否是選定的按鈕。
有沒有更簡單的方法來找出選擇了哪個按鈕? 我正在用 Java 1.3.1 和 Swing 對此進行編程。
我遇到了類似的問題並解決了這個問題:
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
public class GroupButtonUtils {
public String getSelectedButtonText(ButtonGroup buttonGroup) {
for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
}
它返回所選按鈕的文本。
我只是遍歷您的JRadioButtons
並調用isSelected()
。 如果您真的想從ButtonGroup
轉到模型,則只能訪問模型。 您可以將模型與按鈕相匹配,但是如果您可以訪問這些按鈕,為什么不直接使用它們呢?
您必須將setActionCommand
添加到JRadioButton
然后執行以下操作:
String entree = entreeGroup.getSelection().getActionCommand();
示例:
java = new JRadioButton("Java");
java.setActionCommand("Java");
c = new JRadioButton("C/C++");
c.setActionCommand("c");
System.out.println("Selected Radio Button: " +
buttonGroup.getSelection().getActionCommand());
我建議直接采用 Swing 中的模型方法。 將組件放入面板和布局管理器后,甚至不必費心保留對它的特定引用。
如果你真的想要這個小部件,那么你可以用isSelected
測試每個小部件,或者維護一個Map<ButtonModel,JRadioButton>
。
您可以將 actionCommand 放入每個單選按鈕(字符串)。
this.jButton1.setActionCommand("dog");
this.jButton2.setActionCommand("cat");
this.jButton3.setActionCommand("bird");
假設它們已經在 ButtonGroup(在這種情況下為 state_group)中,您可以像這樣獲得所選的單選按鈕:
String selection = this.state_group.getSelection().getActionCommand();
希望這有幫助
以下代碼顯示單擊按鈕時從 Buttongroup 中選擇了哪個 JRadiobutton 。
它是通過循環遍歷特定 buttonGroup 中的所有 JRadioButton 來完成的。
JRadioButton firstRadioButton=new JRadioButton("Female",true);
JRadioButton secondRadioButton=new JRadioButton("Male");
//Create a radio button group using ButtonGroup
ButtonGroup btngroup=new ButtonGroup();
btngroup.add(firstRadioButton);
btngroup.add(secondRadioButton);
//Create a button with text ( What i select )
JButton button=new JButton("What i select");
//Add action listener to created button
button.addActionListener(this);
//Get selected JRadioButton from ButtonGroup
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
Enumeration<AbstractButton> allRadioButton=btngroup.getElements();
while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
JOptionPane.showMessageDialog(null,"You select : "+temp.getText());
}
}
}
}
通常,需要一些與所選單選按鈕相關聯的對象。 它不一定是表示按鈕標簽的String
。 它可以是包含按鈕索引的Integer
或更復雜的類型T
的對象。 您可以按照Tom Hawtin 的建議填充和使用Map<ButtonModel, T>
,但我建議擴展模型並將對象放置在那里。 這是使用這種方法的改進的ButtonGroup
。
import javax.swing.*;
@SuppressWarnings("serial")
public class SmartButtonGroup<T> extends ButtonGroup {
@Override
public void add(AbstractButton b) {
throw new UnsupportedOperationException("No object supplied");
}
public void add(JRadioButton button, T attachedObject) {
ExtendedModel<T> model = new ExtendedModel<>(attachedObject);
model.setSelected(button.isSelected());
button.setModel(model);
super.add(button);
}
@SuppressWarnings("unchecked")
public T getSelectedObject() {
ButtonModel selModel = getSelection();
return selModel != null ? ((ExtendedModel<T>)selModel).obj : null;
}
public static class ExtendedModel<T> extends javax.swing.JToggleButton.ToggleButtonModel {
public T obj;
private ExtendedModel(T object) {
obj = object;
}
}
}
您可以使用此實用程序類代替ButtonGroup
。 創建此類的對象並向其添加按鈕和關聯對象。 例如,
SmartButtonGroup<Integer> group = new SmartButtonGroup<>();
JPanel panel = new JPanel();
for (int i = 1; i <= 5; i++) {
JRadioButton button = new JRadioButton("Button #" + i, i == 3); // select the 3rd button
group.add(button, i);
panel.add(button);
}
在此之后,您可以隨時通過簡單地調用getSelectedObject()
來獲取與當前所選按鈕關聯的對象,如下所示:
int selectedButtonIndex = group.getSelectedObject();
如果您只需要按鈕本身,則可以改用下一個非泛型類。
import javax.swing.JRadioButton;
@SuppressWarnings("serial")
public class RadioButtonGroup extends SmartButtonGroup<JRadioButton> {
public void add(JRadioButton button) {
super.add(button, button);
}
@Override
public void add(JRadioButton button, JRadioButton attachedObject) {
throw new UnsupportedOperationException("Use the short form of addition instead");
}
public JRadioButton getSelectedButton() {
return getSelectedObject();
}
}
您可以使用 ItemSelectable(ButtonModel 的超級接口)的 getSelectedObjects() 返回所選項目的列表。 如果是單選按鈕組,它只能是一個或根本沒有。
將單選按鈕添加到按鈕組,然后:
buttonGroup.getSelection().getActionCommand
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class RadioButton extends JRadioButton {
public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
public Object[] getSelectedObjects() {
if ( isSelected() ) {
return new Object[] { RadioButton.this };
} else {
return new Object[0];
}
}
public RadioButton getButton() { return RadioButton.this; }
}
public RadioButton() { super(); setModel(new RadioButtonModel()); }
public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }
public static void main(String[] args) {
RadioButton b1 = new RadioButton("A");
RadioButton b2 = new RadioButton("B");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
b2.setSelected(true);
RadioButtonModel model = (RadioButtonModel)group.getSelection();
System.out.println(model.getButton().getText());
}
}
使用isSelected()
方法。 它會告訴您單選按鈕的狀態。 將它與循環(例如 for 循環)結合使用,您可以找到已選擇的那個。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyJRadioButton extends JFrame implements ActionListener
{
JRadioButton rb1,rb2; //components
ButtonGroup bg;
MyJRadioButton()
{
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rb1=new JRadioButton("male");
rb2=new JRadioButton("female");
//add radio button to button group
bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
//add radio buttons to frame,not button group
add(rb1);
add(rb2);
//add action listener to JRadioButton, not ButtonGroup
rb1.addActionListener(this);
rb2.addActionListener(this);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new MyJRadioButton(); //calling constructor
}
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}
}
Ale Rojas 的回答很有效:
作為替代方案,您也可以使用My_JRadiobutton11.addActionListener(this);
在你的 JButton 上,然后像這樣在 actionPerformed 函數中執行你的操作(它只使用一個你必須實例化的額外變量(例如私有字符串選擇;)但這沒什么大不了的):
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == My_JRadiobutton11){
//my selection
selection = "Become a dolphin";
}else if(arg0.getSource() == My_JRadiobutton12){
//my selection
selection = "Become a Unicorn";
} ..etc
}
jRadioOne = new javax.swing.JRadioButton();
jRadioTwo = new javax.swing.JRadioButton();
jRadioThree = new javax.swing.JRadioButton();
...然后對於每個按鈕:
buttonGroup1.add(jRadioOne);
jRadioOne.setText("One");
jRadioOne.setActionCommand(ONE);
jRadioOne.addActionListener(radioButtonActionListener);
...聽眾
ActionListener radioButtonActionListener = new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radioButtonActionPerformed(evt);
}
};
...做任何你需要的事情來響應事件
protected void radioButtonActionPerformed(ActionEvent evt) {
System.out.println(evt.getActionCommand());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.