【发布时间】:2017-10-29 15:05:18
【问题描述】:
我必须用三个面板构建UI,leftPanel、middlePanel 和 rightPanel,面板应该对齐 Horizontally
left 和 right 面板应尽可能获得 maximum 和 equal 宽度,而中间面板可以获得 minimum 宽度作为其所需的子组件,一旦添加面板,视图应居中通过中间面板。
我已经完成了以下测试代码来构建 UI
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingTest extends JFrame {
private static final long serialVersionUID = 1L;
public SwingTest() {
setTitle("Swing Test");
setSize(750, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(getParent());
// Rule used to find the component positions, for the testing purpose
Rule rule = new Rule(Rule.HORIZONTAL, true);
rule.setPreferredWidth(10);
rule.setPreferredHeight(40);
SidePanel leftPanel = new SidePanel("Left");
SidePanel rightPanel = new SidePanel("Right");
JPanel middlePanel = new JPanel();
middlePanel.setBorder(BorderFactory.createLineBorder(Color.black));
// Add left,right and middle panel horizontally
JPanel containerPanel = new JPanel();
containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.X_AXIS));
containerPanel.add(leftPanel);
containerPanel.add(middlePanel);
containerPanel.add(rightPanel);
// Add rule and container panel Vertically
JPanel outerPanel = new JPanel();
outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
outerPanel.add(rule);
outerPanel.add(containerPanel);
add(outerPanel);
}
public static void main(String[] args) {
SwingTest test = new SwingTest();
test.setVisible(true);
}
private static class SidePanel extends JPanel {
private static final long serialVersionUID = 1L;
private SidePanel(String text) {
setLayout(new GridBagLayout());
add(new JLabel(text));
}
}
}
我使用了 oracle swing 教程网站上的Rule 类,它可以用来查找组件的位置。获取Rule.java
我遇到的问题如 UI 屏幕截图所示,视图没有被中间面板居中,现在视图居中为“左 + 中面板 = 右面板”的宽度
我不想手动设置面板的高宽,应该由LayoutManager自己处理。
我想要的是中间面板必须以left + middle/2 = middle/2 + right 面板宽度的方式居中。
我找不到使中间面板居中查看的方法,有人可以帮我找到解决方案吗?
【问题讨论】:
标签: java swing layout-manager