如何让两个JPanel总是占用屏幕的一半,水平分割?

前端之家收集整理的这篇文章主要介绍了如何让两个JPanel总是占用屏幕的一半,水平分割?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
标题中所述.我使用BorderLayout()在另一个上面有两个JPanel.
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);
    }
}

它们各占一半,但我怎么能设置它以便它们总是占用JFrame的一半,即使调整大小?
(P.S.我通常使用更好的变量名称,我只是把它作为SSCCE)

解决方法

试试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);
原文链接:https://www.f2er.com/java/130105.html

猜你在找的Java相关文章