Including more than two Panels in a JFrame?

旧城冷巷雨未停 提交于 2019-12-19 03:54:14

问题


We are working on a project where we encountered a problem with including more than two Panels on the same JFrame .What we want is one Panel above the other.

Can the community help give an example of ho to implement this or refer me to a good tutorial or guide related to our Java Swing needs?


回答1:


Assuming you want two panels added to a single frame:

Set a layout for your parent JFrame and add the two panels. Something like the following

JFrame frame = new JFrame();
//frame.setLayout(); - Set any layout here, default will be the form layout
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
frame.add(panel1);
frame.add(panel2);

Assuming you want to add one panel over the other

JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
frame.add(panel1);
panel1.add(panel2);

There is no limit on the number of panels to be added on the JFrame. You should understand that they all are containers when seen on a higher level.




回答2:


if you want each of the frames/panels the same size, use the GridLayout, with a grid of 1(column) and 2(rows)

Frame myFrame;  
GridLayout myLayout = new GridLayout(2,1);  

myFrame.setLayout(myLayout);  

Panel p1;  
Panel p2;  

myFrame.add(p1);
myFrame.add(p2);

if the panels are different size use the BorderLayout.... set the upper frame to "North" and the lower one to "South" or "Center"

Frame myFrame;  

myFrame.setLayout(new BorderLayout() );  

Panel p1;  
Panel p2;  

myFrame.add(p1, BorderLayout.NORTH);  
myFrame.add(p2, BorderLayout.CENTER);  



回答3:


//you can also use card Layout, that enables you to add multiple card-panels on Main panel.

CardLayout cl;
JPanel main,one,two,three;
JButton button1,button2;

cl = new CardLayout();
main.setLayout(cl);

main.add(one,"1");
main.add(two,"2");
main.add(three,"3");

cl.show(main,"1");

public void actionPerformed(ActionEvent e){
 if(e.getSource() == button1)
     cl.show(main,"2");
 else if(e.getSource() == button2)
     cl.show(main,"3");
}


来源:https://stackoverflow.com/questions/2528888/including-more-than-two-panels-in-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!