我尝试了很多不同的布局,但没有一个能给我想要的效果。
我想要这样的东西:
+-----------------------------+
Centered Text
+-------+
|Button |
+-------+
+-----------------------------+
在 html 中它可能看起来像这样:
<p align="center">Some text</p>
<input type="button" value="Press"/>
我遇到的问题是某些布局(BorderLayout)它喜欢调整按钮大小以适应。其他布局(Boxlayout 和 GroupLayout)将执行类似以下操作:
+-----------------------------+
Centered Text
+-------+
|Button |
+-------+
+-----------------------------+
即使我将 JLabel 对齐到 CENTER,将 Button 对齐到 LEFT。
非常感谢我的帮助者。
最佳答案
有很多布局可以实现这一点,事实上,您甚至可以一起使用 BorderLayout
和 FlowLayout
来做到这一点,但是这个示例仅使用 GridBagLayout
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ExampleLayout {
public static void main(String[] args) {
new ExampleLayout();
}
public ExampleLayout() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
JLabel center = new JLabel("Centered Text");
center.setHorizontalAlignment(JLabel.CENTER);
add(center, gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.WEST;
JButton button = new JButton("Button");
add(button, gbc);
}
}
}
看看Laying Out Components Within a Container了解更多示例和详细信息
关于Java GUI 布局不太正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902248/