JPanel,调整大小的问题

dim*_*ads 1 java swing jpanel layout-manager

我是新手。尝试自动调整边框大小。我用 2 个面板在框架上制作了边框。我将带边框的面板添加到第一个面板中。

我想要从所有边缘撤退的边界。在此边框面板中,我还添加了文本面板和按钮。当我扩展窗口或调整其大小时,带有边框的面板也会调整大小。但是当我使用 BorderLayout 时,边缘没有缩进。

public class App {
private JFrame frame;
private JPanel panel;
private JPanel panel_1;
private JTextField textField;
private JButton addBtn;

public static void main(String args[]) {
    App app = new App();

    app.initialize();

    app.frame.pack();
    app.frame.setVisible(true);
}

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 800, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    panel.setLayout(new BorderLayout(0, 0));

    panel_1 = new JPanel();
    panel_1.setPreferredSize(new Dimension(784, 40));
    panel_1.setBorder(new LineBorder(new Color(0, 0, 0)));

    panel.add(panel_1, BorderLayout.CENTER);

    textField = new JTextField();
    textField.setPreferredSize(new Dimension(6, 24));
    panel_1.add(textField);
    textField.setColumns(50);

    addBtn = new JButton("Add");
    addBtn.setPreferredSize(new Dimension(70, 24));
    panel_1.add(addBtn);
}
Run Code Online (Sandbox Code Playgroud)

}

这是与 BorderLayout - http://snag.gy/S43C2.jpg。我还尝试在面板中使用 FlowLayout - http://snag.gy/ndjDG.jpg

你能帮我吗?

Cra*_*ing 5

问题是因为您在添加到的面板上设置了边框BorderLayout.NORTH。当您调整窗口大小时,BorderLayout.NORTH部分只会水平调整大小,这就是边框无法正确调整大小的原因。

public static void main(String args[]) {
    JavaApplication11 app = new JavaApplication11();

    app.initialize();

    app.frame.pack();
    app.frame.setVisible(true);
}

private JFrame frame;
private JPanel panel;
private JTextField textField;
private JButton addBtn;

private void initialize() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    frame.add(panel);

    Border border = new CompoundBorder(new EmptyBorder(5, 10, 15, 20), new LineBorder(Color.BLACK));
    panel.setBorder(border);

    textField = new JTextField(50);
    panel.add(textField);

    addBtn = new JButton("Add");
    panel.add(addBtn);
}
Run Code Online (Sandbox Code Playgroud)