How to have two JPanels that always occupy half the screen each, are divided horizontally?

As described in the title. I have two JPanels one on top of the other using BorderLayout() .

 import java.awt.*; import javax.swing.*; public class myForm(){ public static void main(String[] args) { JFrame myFrame = new JFrame("SingSong"); myFrame.setLocation(100,100); myFrame.setSize(new Dimension(1024,800)); myFrame.setLayout(new BorderLayout()); JPanel jp = new JPanel(); jp.setBackground(new Color(0x00FF00FF)); JPanel jp2 = new JPanel(new BorderLayout()); jp2.setBackground(new Color(0x00000000)); jp.setPreferredSize(new Dimension(100,400)); jp2.setPreferredSize(new Dimension(100,400)); jp2.setLocation(0, 512); myFrame.add(jp2, BorderLayout.SOUTH); myFrame.add(jp, BorderLayout.NORTH); } } 

Each of them takes half, but how can I configure it so that they always occupy half of the JFrame each, even when resizing? (PS I usually use the best variable names, I just hacked it like SSCCE)

+7
source share
2 answers

Try GridLayout

 JFrame myFrame = new JFrame("SingSong"); myFrame.setLocation(100, 100); myFrame.setSize(new Dimension(1024, 800)); GridLayout layout = new GridLayout(2, 1); myFrame.setLayout(layout); JPanel jp = new JPanel(); jp.setBackground(new Color(0x00FF00FF)); JPanel jp2 = new JPanel(new BorderLayout()); jp2.setBackground(new Color(0x00000000)); myFrame.add(jp); myFrame.add(jp2); myFrame.setVisible(true); 
+11
source

when you set PreferredSize, the layout manager will make it so that both panels are always 400 pixels. If you want the panels to always be half the height of the frame, do not set your preferred size. If this does not work, you can always try setting the height of the panels to (myFrame.getSize().height) / 2 , which will be half the height of the frame.

+2
source

All Articles