JPanel Action Listener

后端 未结 3 1719
不知归路
不知归路 2021-01-19 03:56

I have a JPanel with a bunch of different check boxes and text fields, I have a button that\'s disabled, and needs to be enabled when specific configurations are setup. What

3条回答
  •  無奈伤痛
    2021-01-19 04:26

    You need to create custom component listener. Look here:

    Create a custom event in Java

    Creating Custom Listeners In Java

    http://www.javaworld.com/article/2077333/core-java/mr-happy-object-teaches-custom-events.html

    I do it throw the standard ActionListener Example

    public class MyPanel extends JPanel {
      private final  JComboBox combo1;
      private final JButton btn2;
    
      .......
       //catch the actions of inside components
       btn2.addActionListener(new MyPanelComponentsActionListener());
      ........
    
       //assign actionlistener to panel class
        public void addActionListener(ActionListener l) {
            listenerList.add(ActionListener.class, l);
        }
        public void removeActionListener(ActionListener l) {
            listenerList.remove(ActionListener.class, l);
        }
    
        //handle registered listeners from components used MyPanel class
       protected void fireActionPerformed(ActionEvent event) {
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        ActionEvent e = null;
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==ActionListener.class) {
                // Lazily create the event:
                if (e == null) {
                      String actionCommand = event.getActionCommand();
                      if(actionCommand == null) {
                         actionCommand = "FontChanged";
                      }
                      e = new ActionEvent(FontChooserPanel.this,
                                          ActionEvent.ACTION_PERFORMED,
                                          actionCommand,
                                          event.getWhen(),
                                          event.getModifiers());
                 }
                     // here registered listener executing
                    ((ActionListener)listeners[i+1]).actionPerformed(e); 
                }
            }
        }
    
    //!!! here your event generator
        class MyPanelComponentsActionListener implements ActionListener  {
         public void actionPerformed(ActionEvent e) {
            //do something usefull
            //.....
            fireActionPerformed(e); 
          }
         }
    ....
    }
    

提交回复
热议问题