0

I'm deriving a class, let's call it JCustomPanel, from the JPanel class. Several basic properties need to be initiliazed, such as opacity, background color, various listeners, and so on. How should this initialization be done correctly?

The most obvious idea is to do it in the constructor of JCustomPanel. However, all the methods to manipulate these properties (such as setBackgroundColor or addComponentListener) are overridable, and my IDE complains (rightly so, I assume) that overridable methods should not be called in the constructor.

Another option is to define an init method in my JCustomPanel that does all of this work, and then manually call this whenever I create a new JCustomPanel. But this is annoying, and one would be prone to forget to call init, which would introduce errors.

So what's the best practice here?

By the way, I looked at the source code of JList, and it calls setOpaque in its constructor (see here).

Winnie
  • 25
  • 2
  • You "could" make a `private` `init` method, but then it makes it difficult to to extend the class in the future. The reason IDE's complain about calling overridable methods NOW is that it's something that has come to the attention of developers in recent years, back when Java/Swing was been put together, these types of practices weren't really main stream (if genrally recognised at all) – MadProgrammer Jan 10 '16 at 02:25
  • I'm using Eclipse and I don't remember ever seeing such a complaint. What IDE are you using? I'm curious. – user1803551 Jan 10 '16 at 02:47
  • @user1803551 I'm using NetBeans 8.1. – Winnie Jan 10 '16 at 02:48
  • Found [this question](http://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-calls-in-constructors). Could be considered a duplicate. – user1803551 Jan 10 '16 at 03:01
  • @user1803551 Yep, picked that up – MadProgrammer Jan 10 '16 at 03:11
  • Do you get the same message if you call these methods in an initialization block instead of in a constructor? – user1803551 Jan 10 '16 at 03:13
  • @user1803551 I saw that question too. It explains why you can't call overridable methods in the constructor, but I didn't see it give a good solution to the problem I mention. – Winnie Jan 10 '16 at 03:22
  • 1
    @user1803551 No, the warnings go away if the call is made in an initialization block. They also go away if they're put in a private method, as MadProgrammer suggested, even if that method is called from the constructor. However, it seems like even though the IDE doesn't complain, there's the same underlying problem, where an error could happen if these methods are overridden. I probably don't really need to worry much because I'm writing a small program, but I just wanted to know what was considered best practice. – Winnie Jan 10 '16 at 03:25
  • 1
    *"So what's the best practice here?"* Don't extend `JPanel`. Use a factory method to configure it. – Andrew Thompson Jan 10 '16 at 12:59

0 Answers0