java - 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
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.
解决方案
解决复杂计算任务的常用策略是将它们分解为小的、定义明确的可管理任务。分而治之。
这也适用于 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());
}
}
推荐阅读
- javascript - 每次创建新的 chrome 窗口时如何运行脚本?
- javascript - 为什么不刷新页面就不会删除数据表中的数据?
- jhipster - 我可以在远程服务器 (Docker) 中使用共享的 jhipster-registry 和 uaa,开发人员可以将其作为服务连接吗?
- python - 我应该下载哪个版本的 AIDL?
- python - 在另一个数组中逐行搜索一个数组的元素 - Python / NumPy
- python-3.x - 如何最小化arm linux的python3.5.2解释器?
- swift - 使用 @ObservedObject 包装属性形成 NSPredicate 不会返回任何内容。但是,当包装器被移除时,它会返回正确的条目
- reactjs - React - 当父状态更新时重新渲染子组件
- flutter - 如何显示列表
> 何时使用 List.generate 方法?[扑] - swift - Swift / Xcode 奇怪的行为:在声明之前使用结构的情况下显示“使用未声明的类型”错误