监听 ButtonGroup 上的“child”更改,并打印选定的 JRadioButton 的文本

发布于 2024-11-27 08:46:21 字数 85 浏览 7 评论 0原文

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

What I want to is:
Create an event that fires if the a JRadioButton contained in the ButtonGroup is selected, and then print the text there is on the JRadioButton.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北座城市 2024-12-04 08:46:21

根据我的评论,您无法向 ButtonGroup 添加侦听器。您可能必须将 ActionListener 添加到各个 JRadioButton。

如果这不能回答您的问题,请告诉我们有关您问题的更多详细信息。

编辑 1
我想您总是可以扩展 ButtonGroup 以便它接受 ActionListener。例如:

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 方法重写的幕后执行此操作。

As per my comment, you can't add a listener to a ButtonGroup. You will likely have to go with an ActionListener added to the individual JRadioButtons.

If this doesn't answer your question, please tell us more details about your problem.

Edit 1
I suppose you could always extend ButtonGroup such that it accepts ActionListeners. For example:

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

And tested by the following:

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

But this still eventually adds ActionListers to each JRadioButton to achieve its ends; it just does this behind the scenes in the MyButtonGroup's add method override.

深海少女心 2024-12-04 08:46:21

与接受的答案类似的方法,尽管我更喜欢通过 index 控制 ButtonGroup 并检索选择 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 PlugIn 的改编版本

Similar approach as accepted answer, though I prefer to control a ButtonGroup by index and retrieve a selection 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;
}

Applied:

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

Note: @wbp.parser.entryPoint is an adaption for the Eclipse WindowBuilder PlugIn

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文