Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have two JPanels which always take up half the screen each, split horizontally?

Tags:

java

swing

jpanel

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)

like image 546
yoonsi Avatar asked Jul 24 '12 02:07

yoonsi


People also ask

How to set panel layout in Java?

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.

What is border layout in Java?

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 .

Why do we Use panels while creating gui applications in Java?

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.

What is a Java panel?

The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.


1 Answers

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);
like image 159
MadProgrammer Avatar answered Sep 21 '22 20:09

MadProgrammer