我想让我的两个JLabel文本保持左对齐,同时把我的boxLayout放在JFrame的中心。
我尝试了setAlignmentX(CENTER_ALIGNMENT)在我的boxlayout面板,但它没有把我的boxlayout在中心。
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GuiTest extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel jLabelOne = new JLabel();
private JLabel jLabelTwo = new JLabel();
private JPanel panel = new JPanel();
private BoxLayout boxLayout = new BoxLayout(panel,BoxLayout.Y_AXIS);
public GuiTest() {
jLabelOne.setAlignmentX(LEFT_ALIGNMENT);
jLabelTwo.setAlignmentX(LEFT_ALIGNMENT);
jLabelOne.setText("This is text one");
jLabelTwo.setText("This is text two");
panel.setLayout(boxLayout);
panel.add(jLabelOne);
panel.add(jLabelTwo);
panel.setAlignmentX(CENTER_ALIGNMENT);
add(panel);
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(1024,768);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new GuiTest();
}
}
我相信这不会有任何结果:
panel.setAlignmentX(CENTER_ALIGNMENT);
因为你将面板添加到JFrame的contentPane(一个使用BorderLayout的容器),并且实际上是以默认方式添加它,即BorderLayout. center。
考虑给contentPane一个GridBagLayout,并以默认方式添加面板JPanel,它应该居中。只有当它的首选大小小于JFrame的contentPane时,才会看到。
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GuiTest extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel jLabelOne = new JLabel();
private JLabel jLabelTwo = new JLabel();
private JPanel panel = new JPanel();
private BoxLayout boxLayout = new BoxLayout(panel,BoxLayout.Y_AXIS);
public GuiTest() {
panel.setLayout(boxLayout);
jLabelOne.setAlignmentX(CENTER_ALIGNMENT);
jLabelTwo.setAlignmentX(CENTER_ALIGNMENT);
jLabelOne.setText("This is text one");
jLabelTwo.setText("This is text two");
panel.add(jLabelOne);
panel.add(jLabelTwo);
panel.setAlignmentX(CENTER_ALIGNMENT);
add(panel);
setSize(1024,768);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new GuiTest();
}
}
这应该能得到你想要的。