Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...