As described in the title. I've got two JPanels one on top of the other using a 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);
}
}
They each take up half, but how can I go about setting it so that they always take up half the JFrame each, even when resized? (P.S. I normally use better variable names, I just whipped up that as an SSCCE)
You can set a panel's layout manager using the JPanel constructor. For example: JPanel panel = new JPanel(new BorderLayout()); After a container has been created, you can set its layout manager using the setLayout method.
A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. Each region may contain no more than one component, and is identified by a corresponding constant: NORTH , SOUTH , EAST , WEST , and CENTER .
It allows you to group components together, it allows you to devise complex interfaces, as each panel can have a different layout, allowing you to leverage the power of different layout managers.
The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.
Try the 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With