好吧,我有这段代码:
static class things implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame4 = new JFrame("More things");
frame4.setVisible(true);
frame4.setResizable(true);
frame4.setSize(1366,730);
JPanel panel = new JPanel();
JLabel label = new JLabel("<html>One thing more</html>");
label.setVerticalAlignment(SwingConstants.BOTTOM);
label.setHorizontalAlignment(SwingConstants.RIGHT);
panel.add(label);
frame4.add(panel);
}
}
但是当我运行它时,垂直/水平对齐的JLabel不对齐,为什么?
答案 0 :(得分:0)
这是因为LayoutManager
而发生的。详细了解如何使用不同的LayoutManager
's
1)JPanel
默认使用FlowLayout
。在constructor的帮助下,设置为右对齐组件。
2)JFrame
默认使用BorderLayout
。使用参数BorderLayout.SOUTH
将面板添加到其中。
3)在构建GUI时使用frame4.setVisible(true);
以避免伪影。
4)使用pack()
方法,而不是将大小设置为JFrame
。
JFrame frame4 = new JFrame("More things");
frame4.setResizable(true);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JLabel label = new JLabel("<html>One thing more</html>");
panel.add(label);
frame4.add(panel,BorderLayout.SOUTH);
frame4.pack();
frame4.setVisible(true);