Parent JPanel - 如何监听Child JPanel组件生成的事件?

时间:2013-04-01 23:15:40

标签: java swing event-handling jpanel

我制作了一个JPanel Child,里面有几个单选按钮。无论何时单击单选按钮,我都希望从Child生成ActionEvent。此操作事件应“包含”对实际生成事件的按钮的引用。

这个Child将被用作另一个JPanel Parent中的一个组件,它将监听来自Child的事件,而不是收听各个单选按钮。

我该怎么做?

到目前为止

代码 -

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RadioListener extends JPanel implements ActionListener{

public static final String id = "id";

public RadioListener(){

    for(int i = 1; i < 5; i++){
        JRadioButton jrb = new JRadioButton(i + "", false);
        jrb.putClientProperty(id, i);
        this.add(jrb);
        jrb.addActionListener(this);

    }

}


public void actionPerformed(ActionEvent e){

    JRadioButton jrb = (JRadioButton) e.getSource(); 
    Integer id = (Integer) jrb.getClientProperty(RadioListener.id);
    System.out.println("id " + id);

}


public static void main(String[]args){

    JFrame frame = new JFrame("Radio buttons");
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setSize(400, 100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new RadioListener());
    frame.setVisible(true);


}

}

3 个答案:

答案 0 :(得分:3)

我建议提供该组件作为其他感兴趣方注册兴趣的代理的能力。

这意味着您不需要公开其他组件不应该调用或有权访问的方法/组件。

您还应该为侦听器使用内部类,因为它们会阻止其他方法无法访问的其他方法的曝光

public class ProxyActionListener extends JPanel {

    public static final String id = "id";
    private List<JRadioButton> buttons;

    public ProxyActionListener() {

        buttons = new ArrayList<>(25);
        ActionHandler actionHandler = new ActionHandler();

        for (int i = 1; i < 5; i++) {
            JRadioButton jrb = new JRadioButton(i + "", false);
            jrb.putClientProperty(id, i);
            this.add(jrb);
            jrb.addActionListener(actionHandler);
            buttons.add(jrb);

        }

    }

    public void addActionListener(ActionListener listener) {
        for (JRadioButton btn : buttons) {
            btn.addActionListener(listener);
        }
    }

    public void removeActionListener(ActionListener listener) {
        for (JRadioButton btn : buttons) {
            btn.removeActionListener(listener);
        }
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                ProxyActionListener pal = new ProxyActionListener();
                pal.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JRadioButton jrb = (JRadioButton) e.getSource();
                        Integer id = (Integer) jrb.getClientProperty(ProxyActionListener.id);
                        System.out.println("Proxy- id " + id);
                    }
                });

                JFrame frame = new JFrame("Radio buttons");
                frame.getContentPane().setLayout(new FlowLayout());
                frame.setSize(400, 100);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(pal);
                frame.setVisible(true);
            }
        });
    }

    protected class ActionHandler implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            JRadioButton jrb = (JRadioButton) e.getSource();
            Integer id = (Integer) jrb.getClientProperty(ProxyActionListener.id);
            System.out.println("id " + id);

        }
    }
}

答案 1 :(得分:3)

要进一步了解MadProgrammer的建议(1+),您可以使用Swing组件内在的PropertyChangeSupport来实现此目的:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class RadioListenerTesterHFOE extends JPanel {
   private RadioListenerHFOE radioListenerHfoe = new RadioListenerHFOE();

   public RadioListenerTesterHFOE() {
      add(radioListenerHfoe);
      radioListenerHfoe.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent pcEvt) {
            if (pcEvt.getPropertyName().equals(RadioListenerHFOE.RADIO)) {
               System.out.println("Radio Selected: " + pcEvt.getNewValue());
            }
         }
      });
   }

   private static void createAndShowGui() {
      RadioListenerTesterHFOE mainPanel = new RadioListenerTesterHFOE();

      JFrame frame = new JFrame("RadioListenerTesterHFOE");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class RadioListenerHFOE extends JPanel {
   private static final String[] LABELS = {"1", "2", "3", "4"};
   private static final int GAP = 5;
   public static final String RADIO = "radio";
   private ButtonGroup buttonGroup = new ButtonGroup();
   private RadioListenerHandler handler = new RadioListenerHandler();

   public RadioListenerHFOE() {
      setLayout(new GridLayout(1, 0, GAP, 0));
      for (String label : LABELS) {
         JRadioButton radioButton = new JRadioButton(label);
         radioButton.setActionCommand(label);
         radioButton.addActionListener(handler);
         buttonGroup.add(radioButton);
         add(radioButton);
      }      
   }

   private class RadioListenerHandler implements ActionListener {
      private String actionCommand = null;

      @Override
      public void actionPerformed(ActionEvent evt) {
         setActionCommand(evt.getActionCommand());
      }

      private void setActionCommand(String actionCommand) {
         String oldValue = this.actionCommand;
         String newValue = actionCommand;
         this.actionCommand = newValue;
         firePropertyChange(RADIO, oldValue, newValue);
      }
   }

}

答案 2 :(得分:0)

这个解决方案是否足够好?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RadioListener extends JPanel{

public static final String id = "id";
private ActionListener privateActionListener;
JRadioButton[] btns = new JRadioButton[5];

public RadioListener(){

    for(int i = 0; i < btns.length; i++){
        JRadioButton jrb = new JRadioButton(i + "", false);
        jrb.putClientProperty(id, i);
        btns[i] = jrb;
        this.add(jrb);      
    }

}


public static void main(String[]args){

    JFrame frame = new JFrame("Radio buttons");
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setSize(400, 100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    AnActionListener an = new AnActionListener();
    RadioListener rl = new RadioListener();
    rl.setActionListener(an);
    frame.getContentPane().add(rl);
    frame.setVisible(true);


}


public ActionListener getActionListener() {
    return privateActionListener;
}


public void setActionListener(ActionListener privateActionListener) {

    this.privateActionListener = privateActionListener;
    for(int i = 0; i < btns.length; i ++){

        btns[i].addActionListener(privateActionListener);

    }

}



}


class AnActionListener implements ActionListener{

public void actionPerformed(ActionEvent e){

    JRadioButton jrb = (JRadioButton) e.getSource(); 
    Integer id = (Integer) jrb.getClientProperty(RadioListener.id);
    System.out.println("id " + id);

}

}