简体   繁体   中英

Java: Handling event on component inside a separate JPanel component

So I have a JFrame which I've added a custom JPanel component.

The JPanel component has a button that I want to attach a listener to in my JFrame.

What is the best way to do this?

Unless I'm reading this wrong, when you have added the JPanel yourself, you can just add an actionlistener to the button.

JButton.addActionListener(... some listener);

Or is it something else that you are asking here? eg if the custom JPanel is not developed by you. Then in that case, see if the panel exposes an API to add a listener to its buttons, if not then the last option is to iterate over its children to find the JButton:

Component[] comp = customPanel.getComponents();
for(Component c: comp) {
  if(c is a button i am interested in) {
    c.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
           // implement the logic of what happens when button is clicked!
       }
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM