Java:我如何知道组件所在的容器

时间:2013-01-26 20:32:25

标签: java swing

标题有点含糊不清,我将在代码中解释。假设我有

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()会变得很尴尬,因为很难弄清楚它所指的是哪一层面板,而且它违背了封装的想法。

2 个答案:

答案 0 :(得分:4)

使用e.getSource()获取对触发事件的确切组件的引用。在您的情况下,它将是JButton。要获得它所在的面板,请使用e.getSource().getParent()

答案 1 :(得分:1)

说你有B[] bs = new B[n];

然后,您可以为每个按钮设置action command,例如:

for (B b : bs) {
    b.setActionCommand("some identifiable command");    // use different command for different buttons
}

然后在actionPerformed方法中,打开命令:

public void actionPerformed (ActionEvent e) {
    switch (e.getActionCommand()) {
        case "cmd1":
            // do something
            break;
        case "cmd2":
            // do something
            break;
        default:
    }
}

您还可以使用Action个对象,这些对象更灵活但更复杂一些。 有关更多信息,请阅读Java教程: