18

How do I only change the width or height of a component that requires a Dimension object? Currently I do it like this:

jbutton.setPreferredSize(new Dimension(button.getPreferredSize().width, 100));

But I have a feeling that I'm doing it the wrong way. What is the best way to approach this if there is a better way?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Patrick
  • 351
  • 1
  • 4
  • 15
  • 7
    the basic wrong you doing is to call setPreferredSize with whatever dimension ;-) You'll interfere with any internal size hint calculation on part of the component. Simply: dont, never-ever. Instead, use a decent LayoutManager. – kleopatra Aug 24 '11 at 15:06

3 Answers3

21

First of all you are not changing the dimension of JButton. You are specifying the desired preferred size, that can be eventually applied to your JButton depending on the LayoutManager of the component it's inserted into.

For what concern the use of Dimension object that's fine. Eventually you can access directly Dimension field:

Dimension d = button.getPreferredSize();
d.height = 10;
jbutton.setPreferredSize(d); 

but that's pretty much the same thing.

Heisenbug
  • 38,762
  • 28
  • 132
  • 190
  • You made a edit to your question, and it answers the question now. I seem unable to remove the previous comment, so I thank you for your newer answer. – Patrick Aug 24 '11 at 15:06
3

I ended up doing it the way Kleopatra said. Not changing the preferredSize but letting the layout manager do the job. Since this is the proper way to change the size of a component.

Patrick
  • 351
  • 1
  • 4
  • 15
  • 2
    couldn't resist commenting, my grammar compiler is throwing a `SentenceFragment` error (but I'll keep my grubby hands off your post) :) – Ben Feb 16 '12 at 06:50
0

I had the same question but with a different application - I needed to limit the height only, of a JPanel I was adding to a container with a BoxLayout. So when I called setMaximumSize on it and used its PreferredSize for the width, the result was that it did not get the stretching that I expected in the horizontal dimension; it came out shorter because that was its preferred size. I couldn't find what actual width the layout manager was applying, so was at a loss as to what width to use in the new Dimension but the setting I wanted for height worked just fine. The final answer was:

myJPanel.setMaximumSize(new Dimension(<some overly high width value>, <desired height>));

Then the BoxLayout manager gave myJpanel the correct lower width that still filled the container horizontally, and the lower height that I wanted to prevent the vertical stretch.

selofain
  • 11
  • 4