首页 > 解决方案 > How to implement North and South sections in same JPanel

问题描述

Is it possible to have a north and south component in the same JPanel? For example, I want text to display with a 2 x 2 grid layout below. How could I change this code to make that happen? I'm new to Java Swing and am not sure where I should look.

public  CompView(){
super("Super");
setResizable(false);
setLocationRelativeTo(null);

JPanel northPanel = new JPanel();
JPanel middlePanel = new JPanel();
JPanel southPanel = new JPanel();

getContentPane().add(northPanel, BorderLayout.NORTH);
northPanel.add(new JLabel("TITLE", CENTER));
northPanel.setLayout(new GridLayout(2,2));
northPanel.add(new JLabel("Text: "));
northPanel.add(new JTextField());
northPanel.add(new JLabel("Text: "));
northPanel.add(new JTextField());

getContentPane().add(middlePanel, BorderLayout.CENTER);
middlePanel.setLayout(new GridLayout(2,1));
middlePanel.add(new JLabel("Title 2:", CENTER));
middlePanel.add(new JTextField());
}

Current Image

enter image description here

I would like the output to look like this:

| Super             |_|  |X|
----------------------------     --|
|          Title           |       |
----------------------------       |
| Text: | JTextField 1   | |       } North Panel
----------------------------       |
| Text: | JTextField 2   | |       |
----------------------------     --|
|         Title 2          |       |
----------------------------       } Center Panel
| | Resizable JTextField | |       |
----------------------------     --|

Hope this diagram helps.

标签: javaswinglayout-managerborder-layout

解决方案


解决复杂计算任务的常用策略是将它们分解为小的、定义明确的可管理任务。分而治之。
这也适用于 gui:将设计分解为易于布局的小容器。在这种情况下,首先将设计划分为 2 个区域,就像您所做的那样(北和南),然后细分每个区域。例如:

在此处输入图像描述

基本思想是将布局划分为更小的区域,每个区域都有简单的不同布局,可由一个布局管理器实现。

北部的实现可能如下所示:

//avoid extends JFrame. Use for simplification
public class CompView extends JFrame{

    CompView(){

        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel northPanel = new JPanel(new GridLayout(2,0));

        FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER);
        JPanel titlePanel = new JPanel(layout1);
        titlePanel.add(new JLabel("TITLE"));
        northPanel.add(titlePanel);

        FlowLayout layout2 = new FlowLayout(FlowLayout.LEFT);
        JPanel textfieldPanel1 = new JPanel(layout2);
        textfieldPanel1.add(new JLabel("Text: "));
        JTextField txt = new JTextField();
        txt.setColumns(5);
        textfieldPanel1.add(txt);
        northPanel.add(textfieldPanel1);

        add(northPanel, BorderLayout.NORTH);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CompView());
    }
}

推荐阅读