我正在努力实现一些目标like this
问题就在这里,我不知道如何将不同对象的“一列”居中。已尝试使用 GridLayout 和 BorderLayout,但无法使这些元素居中。
如果有人可以帮忙,我将不胜感激。
最佳答案
您可以尝试一下 BoxLayout
- 例如:A Visual Guide to Layout Managers 。有关如何使用此布局管理器的更多详细信息,请参见:How to Use BoxLayout .
如果将组件添加到具有盒式布局的面板,则可以如下设置对齐方式:
component.setAlignmentX(Component.CENTER_ALIGNMENT);
一个完整的例子:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BoxLayoutExample {
public static void main(String[] arguments) {
SwingUtilities.invokeLater(() -> new BoxLayoutExample().createAndShowGui());
}
private void createAndShowGui() {
JFrame frame = new JFrame("Stack Overflow");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(new EmptyBorder(28, 28, 28, 28));
JLabel label = new JLabel("Some longer text here......");
panel.add(label);
label.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createRigidArea(new Dimension(0, 42)));
String text = "image (can be done with \"new ImageIcon(\"image path\")\")";
JLabel image = new JLabel(text);
panel.add(image);
image.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createRigidArea(new Dimension(0, 42)));
JButton button = new JButton("a button");
panel.add(button);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
关于java - JPanel 中央一列三行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441272/