Add an actionListener to a JButton from another class

前端 未结 3 1306
借酒劲吻你
借酒劲吻你 2020-12-12 03:49

so I have two classes testPanel and testFrame. All the buttons are in the testPanel class. I want to add ActionListeners to the Jbuttons in the testFrame class. How do I go

相关标签:
3条回答
  • Here is what you can do :

    1. First create a class that extends JPanel

    2. In that class, define a setActionListener method like this :

    public void setButtonsActionListener(ActionListener listener){
       // and in here set your buttons action listeners
    
       button1.addActionListener(listener);
       button2.addActionListener(listener);
       ...
    
    }
    

    3, In the JFrame class , call the panel's setButtonsActionListener method with an anonymous implementation of the ActionLister interface :

        thePanel.setButtonsActionListener(new ActionListener(){
            @Override
            void actionPerformed(ActionEvent e){
                // here do what you gotta do when the button is clicked
            }
    
        });
    
    0 讨论(0)
  • 2020-12-12 04:30

    Well you could try this (which would require you to have an instance of the testPanel class and the button1 to be set to public:

    testFrame.button1.setActionListener(new ActionListener(@Override public void actionPerformed(ActionEvent event){}});
    

    Or you could make a function inside of the testPanel that sets the action listener.

    0 讨论(0)
  • 2020-12-12 04:34

    First of all, I would be opposed to simply providing public access to the button in the panel, this leads to too many issues with management and scope of responsibility ... IMHO

    You need some kind of reference to the testPane, which would then provide functionality to attach a ActionListener. Then it's up to testPane to manage how that gets done.

    0 讨论(0)
提交回复
热议问题