简体   繁体   中英

Java: How do I know which container a component sits on

The title is a bit ambiguous and I will explain in codes. Suppose I have

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?
     }
}

So is there any way to to that? Or my idea is wrong? Any thought is welcomed.

EDIT: What I finally do is to add a function has(JComponent component) to B to compare against every clickable B has. The getParent() becomes awkward when you have multiple layers of JPanel as it's hard to figure out which layer of panel it's referring to and it's against the idea of encapsulation.

Use e.getSource() to get a reference to the exact component that triggered the event. In your case, it will be a JButton . To get the panel it sits on, use e.getSource().getParent() .

Say you have B[] bs = new B[n];

Then you could set action command for each button, such as:

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

Then in the actionPerformed method, switch on the commands:

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

You can also use Action objects, which is more flexible but a little more complicated. For more information, please read Java tutorial:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM