This is based on one of the examples in Head First Java... it plays some notes using MIDI, and each time a MIDI controller event is fired, it draws a colored rectangle on screen.
Instead of using their rather klugey method of drawing shapes, I created an inner class RectShape so that I could associate some random dimensions with a color, and also conveniently store them in an ArrayList, so that I can redraw the whole lot when the panel needs repainting.
The important bits are the bottom two sections of code.
2 questions about my RectShape class:
1) Is it really bad just to declare its fields and values like this, without using a constructor method?
2) Is it OK to use the fields directly in my JPanel's paintComponent(...) method, since it's an inner class? Or should I still use getters / setters (seems a bit long-winded).
To me it seems more elegant to make the concisest code possible, but you guys might disagree...
For #2, that's really fine as it stands, there's nothing wrong with that. It's pretty much expected that inner classes will directly exchange data with their parents, in one direction or another.
For #1, that's a little harder. Normally, there's no reason not to initialize data members directly if possible, but here, those expressions are awfully long, and makes me a little uncomfortable seeing that big solid block of code at class scope. If it were me, I might define some methods to make those expressions shorter -- for example, a method random(int) that returned a random number less than the given value.
Further, it strikes me as somewhat inconvenient that there's no way to make a "plain" or "default" RectShape, but only to make one containing random values. It would be nice to be able to make one with standard values for testing, for example. This would suggest having multiple constructors: one that makes a random RectShape, and one that initializes to a given list of values.
The warning is telling you that if you were to define a subclass of RectShape, and it were to override random() in such a way that it used the chld class's member variables, then that override could be called at a point before those member variables were initialized -- which is potentially bad. You can make the warning go away by making this impossible; make RectShape final, make random() final, or make random() private. Any of these would prevent random() from being overridden.