program story

ButtonGroup에서 어떤 JRadioButton이 선택되었는지 어떻게 알 수 있습니까?

inputbox 2020. 11. 4. 07:57
반응형

ButtonGroup에서 어떤 JRadioButton이 선택되었는지 어떻게 알 수 있습니까?


양식에 라디오 단추가 포함 된 스윙 응용 프로그램이 있습니다. 내가 가지고있는 ButtonGroup, 그러나, 가능한 방법을보고, 나는 선택의 이름을 얻이 수없는 것 JRadioButton. 지금까지 내가 말할 수있는 것은 다음과 같습니다.

  • ButtonGroup에서를 수행 getSelection()하여 ButtonModel. 거기에서를 수행 할 수 getActionCommand있지만 항상 작동하는 것 같지는 않습니다. 다른 테스트를 시도했지만 예상치 못한 결과를 얻었습니다.

  • 또한에서 ButtonGroup열거 형을 얻을 수 있습니다 getElements(). 그러나 그런 다음 각 버튼을 반복하여 선택했는지 확인하고 확인해야합니다.

어떤 버튼이 선택되었는지 쉽게 확인할 수있는 방법이 있습니까? 저는 이것을 Java 1.3.1과 Swing에서 프로그래밍하고 있습니다.


나는 당신을 반복 JRadioButtons하고 전화 할 것 isSelected()입니다. 당신이 정말로 가고 싶다면 모델로 갈 ButtonGroup수 있습니다. 모델을 버튼과 일치시킬 수 있지만 버튼에 액세스 할 수 있다면 직접 사용하지 않으시겠습니까?


비슷한 문제가 발생하여 다음과 같이 해결되었습니다.

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

선택한 버튼의 텍스트를 반환합니다.


당신은 추가해야합니다 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());

스윙에서 모델 접근 방식을 똑바로 진행하는 것이 좋습니다. 패널 및 레이아웃 관리자에 구성 요소를 넣은 후에는 특정 참조를 유지하지 마십시오.

정말 위젯을 원하면을 사용하여 각각을 테스트 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());  
           }  
        }            
     }
  }

선택된 항목의 목록을 반환하는 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()방법을 사용하십시오 . radioButton의 상태를 알려줍니다. 루프 (예 : 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());
}

}


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

...do whatever you need as response to event

protected void radioButtonActionPerformed(ActionEvent evt) {            
       System.out.println(evt.getActionCommand());
    }

참고URL : https://stackoverflow.com/questions/201287/how-do-i-get-which-jradiobutton-is-selected-from-a-buttongroup

반응형