标题有点模棱两可,我会用代码解释。假设我有
Class A extends JFrame implements ActionListener{
B b;
Class B extends JPanel{
public JButton button;
public B(A a){
button = new JButton();
button.addActionListener(a);// I want to process all actionEvents in A
this.add(button);
}
}
public A(){
b = new B(this);
//irrelevant codes omitted for brevity
}
public void actionPerformed(ActionEvent e){
//Here's the question:
//Suppose I have a lot of Bs in A,
//how can I determine which B the button
//that triggers this callback belongs to?
}
}
那么有什么办法吗?还是我的想法错了?欢迎任何想法。
编辑:我最后要做的是向 B 添加一个函数has(JComponent component)
,以与每个可点击的 B 进行比较。当您拥有多层 JPanel 时,这getParent()
会变得很尴尬,因为很难弄清楚它指的是哪一层面板,而且这与封装的想法背道而驰。