plutoisaplanet
plutoisaplanet

Reputation:

Switching Between Cards in a CardLayout using getParent()

I am writing an application where I am using the CardLayout to swap between two panels that are placed right on top of one another.

There's a JPanel called Top, and it's layout is the CardLayout. Inside this JPanel is a JPanel called CMatch. Whenever the user clicks the submit button in the CMatch panel, I want a new JPanel added to Top that is custom built based on what the user types in, and it will be shown instead of the original CMatch panel. All of this done using the CardLayout.

These are all different classes in different files, however (the panel Top with CardLayout, the panel CMatch that is inside the Top panel, and the custom built panel). So i tried using the following to add the new panel to the Top panel and then have it shown:

(this code takes place in the CMatch class):


    private void submitButtionActionPerformed(ActionEvent e) {
        CardLayout cl = (CardLayout)(this.getParent().getLayout());
        cl.addLayoutComponent(new CChoice(), "college_choices");
        cl.show(this.getParent(), "college_choices");
    }

However, this didn't work. So i was wondering, what am I doing wrong? Any advice is greatly appreciated, thanks!

Upvotes: 0

Views: 1316

Answers (2)

savas ozdemir
savas ozdemir

Reputation: 3

The following works for me:

this.requiredPanelName.setvisible(true) // for required panel
this.otherPanelName.setvisible(false)  // for not required 
this.otherPanelName.setvisible(false) // for not required 

Upvotes: 0

camickr
camickr

Reputation: 324128

Don't know if it makes a difference but I always add components to the Container directly:

String cardName = "college_choices";
Container parent = this.getParent();
parent.add(new CChoice(), cardName); 
CardLayout cl = (CardLayout)parent.getLayout(); 
cl.show(parent, cardName); 

Upvotes: 1

Related Questions