Java JTabbedPane or how to get the custom Object that created the Tab

36 views Asked by At

I am often struggling with the same problem of custom Objects that creates a e.g. gui Component. And I never know what is the best way to get from the gui Component back to the object.

So multiple hacks and tricks are welcome.

Let me explain it to you:

This is my custom Object I need to find afterwards

public class MyObject {
    int yearOfBirth;
    String name;
    public MyObject(int yearOfBirth, String name) {
        this.yearOfBirth = yearOfBirth;
        this.name = name;
    }
    public int getYearOfBirth() {
        return yearOfBirth;
    }
    
    public Component getPanel() {
        Component panel1 = makeTextPanel("This is the personal tab of "+name);
        return panell;
    }
}

This is where I need to find it through the Tab I am focusing

public class MyTabControl implements ChangeListener {
    JTabbedPane myTabPane = new JTabbedPane();
    
    public MyTabControl(){
        //This will add a Listener for clicking on one Tab
        myTabPane.addChangeListener(this);
    }
    
    public void oneMoreTab(MyObject myObject) {
        myTabPane.addTab(myObject.name, myObject.getPanel())
        
    }
    
    public void stateChanged(ChangeEvent arg0) {
        System.out.println("Focus of Tab changed");
        int actualFocusedTabIndex = myTabPane.getSelectedIndex();
        Component acutalFocusedComponent = myTabPane.getComponentAt(actualFocusedTabIndex);
        //This works fine, I can get the Tab. Or at least the Component.
        //But how do I get the yearOfBirth or better the Object itself?
        int yearOfBirthOfTheSelectedTab = ???
    }
}

This is just the main function

public static void main(String[] args) {
    //Commands to start and create the GUI
    
    MyTabControl myTabControl = new MyTabControl();
    
    MyObject mother = new MyObject(1960, "Helen");
    myTabControl.oneMoreTab(mother);
    
    MyObject father = new MyObject(1955, "James");
    myTabControl.oneMoreTab(father);
}

EDIT:

1 not working solution: Extend Component class

I have tried to extend the class Component. But this will create a failure (see comment in code):

public class ComponentWithExtras extends Component {
   MyObject myObject;
   public void addMyObject(MyObject myObject) {
      this.myObject = myObject;
   }
}


// The following line will create failure: Can't cast Component to ComponentWithExtras
ComponentWithExtras componentWithExtras = (ComponentWithExtras) myObject.getPanel();
componentWithExtras.addMyObject(myObject);
myTabPane.addTab(myObject.name, componentWithExtras);
0

There are 0 answers