首页 > 解决方案 > 展开 JFrame 后如何修复 JPanel 的位置

问题描述

我正在尝试使用 Java Swing 制作程序的界面。我有一个容器,我在其中添加了 3 个 JPanel 和一些组件。问题是当我展开框架时,所有这 3 个 JPanel 都在第一行并排出现。

这是我的代码:

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.LineBorder;

public class GraphicRefact extends JFrame {
    private Container container;

    private JButton button2;
    private JButton button1;
    private JTextField textField01;
    private JLabel label01;

    private JButton button03;
    private JButton button04;
    private JTextField textField03;
    private JLabel label03;

    private JButton button02;
    private JButton button01;
    private JTextField textField02;
    private JLabel label02;

    public static void main(String[] args) {
        new GraphicRefact();
    }

    public GraphicRefact() {
        initializeComponents();

        setTitle("Title");
        setSize(500, 150);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        container = new JPanel();


        JPanel panel01 = new JPanel();

        panel01.add(label01);
        panel01.add(textField01);
        panel01.add(button2);
        panel01.add(button1);
        panel01.setBorder(new LineBorder(Color.BLACK, 3));
        container.add(panel01);



        JPanel panel02 = new JPanel();

        panel02.add(label02);
        panel02.add(textField02);
        panel02.add(button02);
        panel02.add(button01);
        container.add(panel02);

        JPanel panel03 = new JPanel();

        panel03.add(label03);
        panel03.add(textField03);
        panel03.add(button03);
        panel03.add(button04);
        container.add(panel03);

        add(container);

    }

    private void initializeComponents() {

        button1 = new JButton("Open");
        button2 = new JButton("Close");
        textField01 = new JTextField("Choose the path...");
        label01 = new JLabel("Choose File: ");

        button01 = new JButton("Button01");
        button02 = new JButton("Button02");
        textField02 = new JTextField("Choose the path...");
        label02 = new JLabel("Choose Dir:");

        button03 = new JButton("Button03");
        button04 = new JButton("Button03");
        textField03 = new JTextField("Choose the path...");
        label03 = new JLabel("Choose Dir:");
    }

}

这是程序在展开框架之前和之后的样子。

前:

在此处输入图像描述

后:

在此处输入图像描述

因此,即使在展开框架之后,我也希望程序将这 3 个 JPanel 留在容器的中间。

谢谢!

标签: javaswingjpanellayout-managerflowlayout

解决方案


您必须使用正确的LayoutManager。看看那里的例子。BoxLayout 似乎是您想要的。


推荐阅读