1

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 があり、それぞれに 4 つのラジオ ボタンがあります。そう(80個のラジオボタン)。

4

5 に答える 5

3
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.
}
于 2011-11-22T18:35:26.507 に答える
2

この問題に直面している理由は、(ループではなく) すべての 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(...);
    }
}
于 2011-11-22T18:23:05.693 に答える
2

ラジオボタンごとに個別にアクションリスナーを定義する代わりに、すべてのラジオボタンに共通のアクションリスナーを定義する必要があります。

例えば

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()なく、アクションに関連付けられたコマンド文字列を返します。

于 2011-11-22T18:21:36.273 に答える