Java JPanel的中心有一列和三行
我正在努力取得一些成就 问题是,我不知道如何将不同对象的“一列”居中。已尝试使用GridLayout和BorderLayout,但无法使这些元素居中Java JPanel的中心有一列和三行,java,swing,layout,Java,Swing,Layout,我正在努力取得一些成就 问题是,我不知道如何将不同对象的“一列”居中。已尝试使用GridLayout和BorderLayout,但无法使这些元素居中 如果有人能帮忙,我将不胜感激 您可以尝试一下BoxLayout,例如:。有关如何使用此布局管理器的详细信息,请参见: 如果将构件添加到具有长方体布局的配电盘中,可以如下所示设置对齐方式: component.setAlignmentX(Component.CENTER_ALIGNMENT); 一个完整的例子: import java.awt.*
如果有人能帮忙,我将不胜感激 您可以尝试一下
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);
}
}
你有密码吗?我会认真考虑边界布局。北、南、中。这应该能奏效。