所以我有一个JFrame,我已经添加了一个自定义的JPanel组件。
JPanel组件有一个按钮,我想在我的JFrame中附加一个监听器。
这样做的最佳方式是什么?
答案 0 :(得分:2)
除非我读错了,否则当你自己添加JPanel时,你只需在按钮上添加一个actionlistener。
JButton.addActionListener(... some listener);
或者你在这里问的其他事情是什么?例如如果自定义JPanel不是由您开发的。然后在这种情况下,看看面板是否公开了一个API来为其按钮添加一个监听器,如果没有,那么最后一个选项是遍历其子节点以找到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!
}
});
}
}