本文介绍了确定选择什么 JRadioButton 的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在以这种方式获取选定的按钮,但如果这是正确/最好的方法,我不会.也许还有比这更容易或面向对象的东西.

Currently I'm getting the selected button in this way, but I don't if this is the right/best method. MAybe there something more easy or object oriented than this.

private int getFilterType(JRadioButton... buttons) {
    for (int i = 0, n = buttons.length; i < n; i++) {
        if (buttons[i].isSelected()) {
            return i + 1;
        }
    }
    return buttons.length + 1;
}

推荐答案

为此我喜欢使用 ButtonGroup 本身.即,

I like using the ButtonGroup itself for this. i.e.,

import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;

public class ButtonModelEg {
   public static final String[] BUTTON_TEXTS = {"Fe", "Fi", "Fo", "Fum"};

   private static void createAndShowUI() {
      final ButtonGroup btnGroup = new ButtonGroup();

      JPanel panel = new JPanel(new GridLayout(0, 1));
      for (String btnText : BUTTON_TEXTS) {
         JRadioButton radioBtn = new JRadioButton(btnText);
         radioBtn.setActionCommand(btnText);
         btnGroup.add(radioBtn);
         panel.add(radioBtn);
      }

      final JTextField selectionField = new JTextField();

      JButton button = new JButton(new AbstractAction("Get Choice"){
         public void actionPerformed(ActionEvent arg0) {
            // get the button model selected from the button group
            ButtonModel selectedModel = btnGroup.getSelection();
            if (selectedModel != null) {
               // and dislay it
               selectionField.setText(selectedModel.getActionCommand());
            }
         }
      });

      panel.add(button);
      panel.add(selectionField);

      JFrame frame = new JFrame("ButtonModelEg");
      frame.getContentPane().add(panel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

这篇关于确定选择什么 JRadioButton 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 19:47