如标题中所述。我有两个使用 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);

关于java - 如何让两个 JPanel 始终占据屏幕的一半,水平分割?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11623260/

10-12 04:57