JPanel Action Listener

后端 未结 3 1681
不知归路
不知归路 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:21

    A suggestion could be to derive a class from each of the components you're using and add an ActionListener that bubbles up the Container tree and looks for the first Container that implements a custom interface like this:

    public interface MyCommandProcessor {
      void execute(String actionCommand);
    }
    
    public class MyButton extends JButton {
      public MyButton(string actionCommand) {
        setActionCommand(actionCommand);
        addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent ae) {
            Container traverser = MyButton.this;
            while (traverser != null && !(traverser instanceof MyCommandProcessor))
              traverser = traverser.getParent();
            if (traverser != null)
              ((CommandListener)traverser).execute(ae.getActionCommand());
          }
        });
      }
    }
    
    public class MyApp extends JFrame implements MyCommandListener {
      public MyApp() {
        JPanel panel = new Panel();
        panel.add(new MyButton("MyButton got pressed"));
      }
    
      public void execute(String actionCommand) {
        System.out.println(actionCommand);
      }
    }
    

提交回复
热议问题