Andy Hin
Andy Hin

Reputation: 31893

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?

Upvotes: 0

Views: 202

Answers (1)

naikus
naikus

Reputation: 24472

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? e.g. 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!
       }
    });
  }
}

Upvotes: 2

Related Questions