我必须建立一个UI
具有三个面板,leftPanel
, middlePanel
和rightPanel
,面板应对齐 Horizontally
left
和right
面板应获得 maximum
和equal
宽度尽可能的同时中间面板可以得到 minimum
width 作为其子组件所需的宽度,添加面板后 View 应以中间面板居中。
我已经完成了以下测试代码来构建 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));
}
}
}
我用过Rule
来自 oracle swing 教程站点的类,它可用于查找组件的位置。获取Rule.java
我遇到的问题如 UI 屏幕截图所示, View 未以中间面板居中,现在 View 以“左 + 中面板 = 右面板”的宽度为中心
我不想手动设置面板高度和宽度,它应该由 LayoutManager
处理本身。
我想要的是中间面板必须以某种方式居中left + middle/2 = middle/2 + right
面板宽度。
我找不到使中间面板居中查看的方法,有人可以帮我找到解决方案吗?
最佳答案
您需要了解 BoxLayout 的工作原理。
第一个空间按照每个组件的首选大小分配。然后,如果有额外空间,则将该空间分配给每个组件。
中间似乎没有居中,因为右侧标签的首选尺寸大于左侧标签。因此,当分配额外空间时,右侧大于左侧。
这很容易测试。只需将右侧面板的文本更改为“LEFT”即可。
然而,这又引出了另一个问题——为什么中间面板的大小没有改变?我不知道这个问题的答案。尽管由于某种原因,默认的 FlowLayout 的工作方式似乎与 GridBagLayout 不同。您可以再次通过将中间面板的布局更改为 GridBagLayout 来测试这一点。
如果您始终希望左/右面板大小相同,那么您可能需要考虑使用 Relative Layout 。使用此布局的基本代码将是:
RelativeLayout rl = new RelativeLayout(RelativeLayout.X_AXIS);
JPanel panel = new JPanel( rl );
panel.add(leftPanel, new Float(1));
panel.add(middle, new Float(3));
panel.add(rightPanel, new Float(1));
现在左/右面板将具有相同的尺寸,与添加到每个面板的组件无关。
关于java - 如何通过 Swing 中的中间面板使 View 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001721/