使用SpringLayout时为什么JLabel的高度为零?

时间:2017-08-14 18:10:15

标签: java swing jlabel springlayout

我是Java UI设计的新手,我尝试使用SpringLayout来创建表单。 我将JLabel放在JFrame中,添加了一些约束。我需要JLabel stratches到JPanel宽度。但它的高度为零。而且宽度太小。

这是代码片段:

imageContainer = new JLabel();
imageContainer.setBorder(BorderFactory.createLineBorder(Color.BLACK));

filterButton = new JButton("Filter");
filterButton.addActionListener(filter);

layout.putConstraint(SpringLayout.WEST, imageContainer, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, imageContainer, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.EAST, imageContainer, 5, SpringLayout.EAST, this);

layout.putConstraint(SpringLayout.WEST, filterButton, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, filterButton, 5, SpringLayout.SOUTH, imageContainer);
layout.putConstraint(SpringLayout.SOUTH, filterButton, 5, SpringLayout.SOUTH, this);

这是result

我哪里出错了?如何将JLabel大小拉伸到父容器?

1 个答案:

答案 0 :(得分:0)

我的问题不在于JLablel。 我试图在约束中使用 this ,但实际上这不是正确的方法。你需要得到这样的容器:

Container contentPane = this.getContentPane();

之后,您可以在约束中使用contentPane:

layout.putConstraint(SpringLayout.WEST, imageContainer, 5, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, imageContainer, 5, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.EAST, imageContainer, -5, SpringLayout.EAST, contentPane);
layout.putConstraint(SpringLayout.SOUTH, imageContainer, -5, SpringLayout.NORTH, filterButton);

layout.putConstraint(SpringLayout.WEST, filterButton, 5, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.SOUTH, filterButton, -5, SpringLayout.SOUTH, contentPane);

这项工作。