【发布时间】:2016-02-24 12:21:12
【问题描述】:
我正在尝试将几个 JTextField、JButton 和 JLabels 添加到面板中,但是只显示按钮。我已将 JPanel 的布局设置为空,并为每个项目设置了位置/边界。
frame= new JFrame("Find and Replace");
JPanel panel = new JPanel(null);
JLabel findLabel = new JLabel("Find:");
findLabel.setLocation(0, 20);
JLabel replaceLabel = new JLabel("Replace with:");
replaceLabel.setLocation(50, 60);
findField = new JTextField(20);
findField.setLocation(30, 100);
replaceField = new JTextField(20);
replaceField.setLocation(220, 140);
replaceAllButton = new JButton("Find and Replace All");
replaceAllButton.setBounds(20, 200, 100, 25);
replaceButton = new JButton("Replace");
replaceButton.setBounds(120, 200, 100, 25);
panel.add(findLabel);
panel.add(findField);
panel.add(replaceLabel);
panel.add(replaceField);
panel.add(replaceButton);
panel.add(replaceAllButton);
【问题讨论】:
-
“缺失”组件的大小为 0。但是,真正的问题是使用
null布局。使用布局管理器,因为 swing 是为使用而设计的,组件的大小将自动确定,窗口在调整大小时表现良好,等等。null布局乍一看可能看起来更容易,但会带来无穷无尽的麻烦。 -
嗯,我该如何使用 GroupLayout 呢?我在这里看到了一些不同布局的例子,docs.oracle.com/javase/tutorial/uiswing/layout/visual.html,对我来说 GroupLayout 看起来很不错
-
GroupLayout可能有效,但手动使用相当困难。我更喜欢组合布局,而不是试图一次解决整个布局问题。