0

I new in Java UI design and I try to use SpringLayout to create form. I put JLabel in JFrame, added some constraints. I need JLabel that stratches to JPanel width. But it has zero height. And too small width.

Here is code fragment:

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);

And this is the result

Where did I go wrong? How to stretch JLabel size to parent container?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    *"Here is code fragment:"* For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). BTW - until a label contains an icon &/or text, its preferred size will be 0x0. – Andrew Thompson Aug 14 '17 at 18:20
  • I want to put image in JLabel later. But I need to know JLabel size if I want to stratch (scale) an image. – Андрей Яндуганов Aug 15 '17 at 06:29
  • Where is the MCVE? BTW - The label will return a preferred size based on the content (e.g. an image). Probably better to approach this by custom painting the image in a `JPanel` that has overridden the method to `getPreferredSize()` to produce a logical minimum value. Then 1) the panel will be assigned space by the layout. 2) the custom painting can draw the image based upon the size the panel ends up at. – Andrew Thompson Aug 15 '17 at 10:35

1 Answers1

0

My problem not in JLablel. I attempted to use this in constraints but really it's not correct way. You need to get container like this:

Container contentPane = this.getContentPane();

After that you can use contentPane in constraints:

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);

And this work.