Including more than two panels in a JFrame?

We are working on a project in which we are faced with the problem of including more than two panels in the same JFrame. We want one panel over another.

Can the community help provide an example ho to implement this, or give me a good tutorial or guide related to our Java Swing requirements?

+4
source share
3 answers

Assuming two panels are added to the same frame:

Set the layout for the parent JFrame and add 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 on top of another

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

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

+7
source

if you want each frame / panel to be the same size, use a 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 of different sizes, use BorderLayout .... set the top frame to "North" and the bottom to "South" or "Center"

 Frame myFrame; myFrame.setLayout(new BorderLayout() ); Panel p1; Panel p2; myFrame.add(p1, BorderLayout.NORTH); myFrame.add(p2, BorderLayout.CENTER); 
+2
source

// you can also use the map layout, which allows you to add several card panels to the 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"); } 
+2
source

Source: https://habr.com/ru/post/1305299/


All Articles