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
297 views
in Technique[技术] by (71.8m points)

java - Make an added JPanel visible inside a parent JPanel

How to make an added JPanel visible inside a parent JPanel?

I am using Netbeans for designing my UI.

I have a MainFrame.java, which contains two panels; namely headerPanel and bodyPanel.

In headerPanel I have put three buttons,let it be button1, button2 and button3.

Also I have created three separate files extending JPanel, name it panel1, panel2 and panel3.

Then I added all my three panels inside bodypanel in MainFrame.java in constructor.

bodyPanel.add(panel1);
bodyPanel.add(panel2);
bodyPanel.add(panel3);

I want that on clicking the respective buttons only respective panels should appear in the bodypanel in mainframe, i.e. if I click button1 then panel1 should be displayed.

I have already tried the following code in button1 mouse listener method:

bodyPanel.validate();
bodyPanel.getComponent(0).setVisible(true);

But panel1 does not appear. I did it cause added components in a panel are allotted index. So first I tried to get the components and then make it visible. It did not work.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use a CardLayout, as shown here.

Game view High Scores view


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

...