开发者

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 开发者_Python百科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? 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!
       }
    });
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜