将 JLabel 定位在角落
Positioning JLabel in Corner
我在布局方面很笨...对于我的应用程序,我想在 bottom-left 角落放置一个面板,并带有填充,但我不确定要使用哪种布局。
我尝试使用结合水平对齐的 BorderLayout 将面板定位在角落,但没有产生预期的结果。我的代码如下:
final JLabel label = new JLabel();
label.setBorder(new EmptyBorder(20, 20, 20, 20));
label.setHorizontalAlignment(JLabel.LEFT);
label.setPreferredSize(new Dimension(100,100));
label.setBackground(Color.WHITE);
label.setOpaque(true);
add(label, BorderLayout.SOUTH);
(外部 class 扩展了 JFrame)
下图详细说明了我想要什么,以及我拥有什么。
实现此布局有什么技巧吗?这看起来很简单,但我还是布局新手
您可以使用空布局来自定义您的 JFrame。
yourFrame.setLayout(null)
你可以
setLocation(x,y);
setsize(width,height);
您可以使用 SpringLayout
.
这很棘手,但它会成功的。
SpringLayout springLayout = new SpringLayout();
Container cont = getContentPane();
cont.setLayout(springLayout);
JLabel label = new JLabel("New label");
springLayout.putConstraint(SpringLayout.WEST, label, 20, SpringLayout.WEST, cont);
springLayout.putConstraint(SpringLayout.SOUTH, label, -10, SpringLayout.SOUTH, cont);
cont.add(lblNewLabel);
Spring 布局允许您设置组件边和框架之间的距离,并最终以动态方式设置它的位置(调整大小时位置将保持相对于框架)
这是输出:
我推荐两种方式:
您可以使用GridBagLayout
来实现您想要的。查看教程 here。
它足够灵活,可以满足您的需求以及任何其他附加组件。
使用不同布局的嵌套面板。例如,topPanel 和 bottomPanel。默认情况下(FlowLayout 将用于您的 bottomPanel)这会将 JLabel 定位在左下角。
我在布局方面很笨...对于我的应用程序,我想在 bottom-left 角落放置一个面板,并带有填充,但我不确定要使用哪种布局。
我尝试使用结合水平对齐的 BorderLayout 将面板定位在角落,但没有产生预期的结果。我的代码如下:
final JLabel label = new JLabel();
label.setBorder(new EmptyBorder(20, 20, 20, 20));
label.setHorizontalAlignment(JLabel.LEFT);
label.setPreferredSize(new Dimension(100,100));
label.setBackground(Color.WHITE);
label.setOpaque(true);
add(label, BorderLayout.SOUTH);
(外部 class 扩展了 JFrame)
下图详细说明了我想要什么,以及我拥有什么。
实现此布局有什么技巧吗?这看起来很简单,但我还是布局新手
您可以使用空布局来自定义您的 JFrame。
yourFrame.setLayout(null)
你可以
setLocation(x,y);
setsize(width,height);
您可以使用 SpringLayout
.
这很棘手,但它会成功的。
SpringLayout springLayout = new SpringLayout();
Container cont = getContentPane();
cont.setLayout(springLayout);
JLabel label = new JLabel("New label");
springLayout.putConstraint(SpringLayout.WEST, label, 20, SpringLayout.WEST, cont);
springLayout.putConstraint(SpringLayout.SOUTH, label, -10, SpringLayout.SOUTH, cont);
cont.add(lblNewLabel);
Spring 布局允许您设置组件边和框架之间的距离,并最终以动态方式设置它的位置(调整大小时位置将保持相对于框架)
这是输出:
我推荐两种方式:
您可以使用
GridBagLayout
来实现您想要的。查看教程 here。 它足够灵活,可以满足您的需求以及任何其他附加组件。使用不同布局的嵌套面板。例如,topPanel 和 bottomPanel。默认情况下(FlowLayout 将用于您的 bottomPanel)这会将 JLabel 定位在左下角。