3

How to set java swing component size to its enclosing parent size. ex: setting JLabel size to its enclosing JPanel size.

Like android's Wrap_parent option.

Vishwanath gowda k
  • 1,675
  • 24
  • 26
  • See [**this answer**](http://stackoverflow.com/a/21376596/2587435) for which components _stretch_ children and which don't – Paul Samsotha Feb 16 '14 at 16:40

2 Answers2

2

On the enclosing parent call .setLayout(new BorderLayout());. The component in the center (default) cell of a BorderLayout is forced to match the size of its container.

Boann
  • 48,794
  • 16
  • 117
  • 146
-1

One way to go about it is to override doLayout() in the parent. In that method you can set the bounds of the label the way you like.

Janos
  • 1,987
  • 3
  • 17
  • 24
  • -1, There should be no reason to override doLayout(). That is done for custom components like JTable. Swing was designed to use layout managers. If you need a custom layout then create a custom layout managers. However, there should be no need to create a custom layout since many of the Swing layout manager will provide the required functionality. – camickr Feb 16 '14 at 18:34
  • for one thing, the BorderLayout based solution recommended above will NOT work if there's any other component in the other compartments of the parent container. doLayout while I agree is a questionable solution is actually quite handy in a few situations. and as a non final method, the API design does not suggest that one should not use it. – Janos Feb 17 '14 at 12:16
  • Sure it will still work. Components in the NORTH, SOUTH, EAST and WEST will take up the space they need. The rest of the space will go to the CENTER so the label will take up that space whatever that may be. Your suggestion is definitely questionable and in no way needed to solve the problem, especially when there are much simpler and straight forward solutions available. – camickr Feb 17 '14 at 16:07
  • The original question was: How to set java swing component size to its enclosing parent size. If there are other components in the parent container (which is a BorderLayout) you will NOT be able to size your compnent to its full size by putting it into the CENTER, as those other components taking up space. – Janos Feb 18 '14 at 06:55
  • If you want the component to take up all the space of the panel, then why are you adding other components to the panel? However, even with you complicate view of the question you could easily create a JPanel with a BorderLayout add one component to the WEST, then create another panel with a BorderLayout. Add the label to this panel, then add then second panel to the first. Now you have met you requirement of the label taking all the space in the panel. But that would be an unnecessarily complicated solution. – camickr Feb 18 '14 at 18:51