1

Let's say I got a class that inherits from JPanel, named SomePanel. This class overrides paintComponent() and draws in it a Rectangle. An instance of this class is added to a JFrame.

What's the difference between overriding getPreferredSize(Dimension) inside SomePanel, and calling instanceOfSomePanel.setPreferredSize(Dimension) from the JFrame?. The both acheive the same thing, don't they?

Josh
  • 95
  • 1
  • 9
  • if you override `getPrefferedSize` you sure break liskov substitution principle, people override it cause layout managers. Read more [here](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi/7229519#7229519) – nachokk Dec 26 '13 at 19:01
  • Moreover, you substitute _your_ calculation for that of the component's UI delegate. – trashgod Dec 26 '13 at 19:15

1 Answers1

1

The reason you are creating a custom component is to do custom painting of a Rectangle. The size of the Rectangle that you want to paint becomes a property of your component. Therefore your component should also be responsible for determining the proper size of the component, which would be based on the size of the Rectangle you want to paint. So you override the getPreferredSize() method to make sure the component paints properly.

For example if you are painting a Rectangle like the Rectangle in you last question:

Rectangle rect = new Rectangle(50,50,50,50);

then the preferred size should probably be (150, 150) so that the Rectangle has equally sized border around the entire component.

If you leave this to the programmer using your component they may do something like:

somePanel.setPreferredSize( new Dimension(50, 50) );

Now the component will not paint properly because the programmer just used a random size.

camickr
  • 321,443
  • 19
  • 166
  • 288