java 监听ButtonGroup的“子”更改,并打印所选JRadioButton的文本

cnjp1d6j  于 2023-06-20  发布在  Java
关注(0)|答案(2)|浏览(143)

我想要的是:创建一个事件,如果选择了ButtonGroup中包含的JRadioButton,则触发该事件,然后打印JRadioButton上的文本。

7gyucuyw

7gyucuyw1#

根据我的评论,你不能向ButtonGroup添加侦听器。您可能需要将ActionListener添加到各个JRadioButton中。
如果这不能回答您的问题,请告诉我们有关您的问题的更多细节。

    • 编辑1**

我想你总是可以 * 扩展 * ButtonGroup,让它接受ActionListeners。例如:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.event.EventListenerList;

@SuppressWarnings("serial")
public class MyButtonGroup extends ButtonGroup {
   private ActionListener btnGrpListener = new BtnGrpListener();
   private EventListenerList listenerList = new EventListenerList();

   @Override
   public void add(AbstractButton b) {
      b.addActionListener(btnGrpListener);
      super.add(b);
   }

   public void addActionListener(ActionListener listener) {
      listenerList.add(ActionListener.class, listener);
   }

   public void removeActionListener(ActionListener listener) {
      listenerList.remove(ActionListener.class, listener);
   }

   protected void fireActionListeners() {
      Object[] listeners = listenerList.getListenerList();
      String actionCommand = "";
      ButtonModel model = getSelection();
      if (model != null) {
         actionCommand = model.getActionCommand();
      }
      ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, actionCommand);
      for (int i = listeners.length-2; i>=0; i-=2) {
          if (listeners[i]== ActionListener.class) {
              ((ActionListener)listeners[i+1]).actionPerformed(ae);
          }
      }
   }

   private class BtnGrpListener implements ActionListener {

      public void actionPerformed(ActionEvent ae) {
         fireActionListeners();
      }
   }
}

并通过以下测试:

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

import javax.swing.*;

public class MyButtonGroupTest {
   private static void createAndShowUI() {
      String[] data = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

      JPanel panel = new JPanel(new GridLayout(0, 1));
      MyButtonGroup myBtnGrp = new MyButtonGroup();
      myBtnGrp.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            System.out.println("Action Command is: " + e.getActionCommand());
         }
      });

      for (String text : data) {
         JRadioButton radioBtn = new JRadioButton(text);
         radioBtn.setActionCommand(text);
         myBtnGrp.add(radioBtn);
         panel.add(radioBtn);
      }

      JFrame frame = new JFrame("MyButtonGroupTest");
      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();
         }
      });
   }
}

但这最终仍然会将ActionListers添加到每个JRadioButton中以实现其目的;它只是在MyButtonGroup的add方法覆盖中在幕后完成此操作。

42fyovps

42fyovps2#

类似的方法作为公认的答案,虽然我更喜欢控制一个ButtonGroup * index * 和检索一个选择 * index *。

/**
 * Extend javax.swing.ButtonGroup with Listener
 * @author Sam Ginrich
 *
 */
@SuppressWarnings("serial")
public class ButtonGroupWL extends ButtonGroup implements ActionListener
{

    /**
     * @wbp.parser.entryPoint
     */
    public ButtonGroupWL(AbstractButton... buttons)
    {
        super();
        listeners = new ArrayList<Listener>();
        for (AbstractButton b : buttons)
        {
            add(b);
        }
    }

    static public interface Listener
    {
        void onNewSelection(AbstractButton sel, int btnIndex);
    }

    public void select(int index)
    {
        buttons.get(index).setSelected(true);
    }

    @Override
    public void add(AbstractButton button)
    {
        super.add(button);
        button.addActionListener(this);
    }

    @Override
    public void remove(AbstractButton button)
    {
        button.removeActionListener(this);
        super.remove(button);
    }

    public void addListener(Listener listener)
    {
        listeners.add(listener);
    }

    public void removeListener(Listener listener)
    {
        listeners.remove(listener);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        Object src = e.getSource();
        int index = super.buttons.indexOf(src);
        if (index < 0)
        {
            return;
        }
        for (Listener l : listeners)
        {
            l.onNewSelection((AbstractButton) src, index);
        }
    }
    protected List<Listener> listeners;
}
    • 申请:**
JRadioButton rdbtnLocalRepo, rdbtnRemoteRepo;
 
// ...

buttonGroup = new ButtonGroupWL(rdbtnLocalRepo, rdbtnRemoteRepo);
buttonGroup.select(0); // Initial selection
buttonGroup.addListener(new ButtonGroupWL.Listener()
{
    @Override
    public void onNewSelection(AbstractButton sel, int btnIndex)
    {
        System.out.println("Button " + btnIndex + " selected");
    }
});
    • 注意:**@wbp. parser. entryPoint是Eclipse WindowBuilder插件的适配

相关问题