Dimension, Only changing the width/height

Patrick picture Patrick · Aug 24, 2011 · Viewed 11.9k times · Source

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?

Answer

Heisenbug picture Heisenbug · Aug 24, 2011

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.