简体   繁体   中英

Clarification in reaching components, Java Swing

I'm relatively new to using the javax.swing and java.awt so bear with me if I express my problem awkwardly.

Let's say I have a custom made class CustomClass that extends and creates a JPanel p . In the class I add a JButton b to p . Later in another program file I create an instance of my CustomClass called cp and want to be able to catch for example a click event from b using the “actionPerformed” method. My question is how do I “reach” (like the written path to) the JButton b from instance cp ? (Assuming that all relevant class files are already associated)

Use getters and setters if i understood correctly. I,e your customPanel will have a public getButton() method which would return the JButton instance:

class CustomPanel extends JPanel {
    JButton button=new JButton("Some button");

    public JButton getMyButton() {
        return button;
    }
}

class Test {
    CustomPanel cp=new CustomPanel();


    void someMethod() {
       JButton b= cp.getMyButton();
    }
}

UPDATE

as per comment:

what if I have like 10 or 20 different components in my JPanel, is there some way to reach them without having to make a lot of methods

Simply call getComponentCount on JPanel instance and than iterate using a for loop and getComponentAt(int i) this will allow you to get access to all components on JPanel :

CustomPanel cp=...;//this class extends jpanel


for(int i=0;i<cp.getComponentCount();i++) {
    Component c=cp.getComponentAt(i);
     if( c instanceof JButton) {
         //do something
    }
 }

UPDATE 2

What if I have two or more objects that should be of the same class but otherwise treated as separate objects, how can I tell them apart using the loop that you've provided me

look at setName(String name) and getName of JButton this will allow you to assign the instance a unique name which can be gotten by getName() . Alternatively use setActionCommand(String name) and getActionCommand() to differentiate the buttons from another I prefer the latter. Or you could even use their texts, via getText()

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