Java Notes

Where to declare components

Components are typically declared in one of several places:

Field variables

Some components should be declared as field variables (instance variables, member variables). This is the appropriate place to declare components which must be referenced after the interface is constructed. Typically these are text fields or text areas, check boxes, etc. Those components whose values must be gotten or set.

Local variables

Local variables should be used for components which are never referenced after the interface is constructed. Typically these are panels for holding components, buttons (whose interaction is thru their listeners), ... Local variables disappear when the method they are in returns, but the component will continue to exist if it has been added to the interface.

Anonymous

Anonymous creation is typical with labels, which can be created and added in one step and never assigned to a variable. Of course, if the appearance (font, alignment, ...) must be changed, then they should be put in a local variable. Some programs use labels for output (not a good idea), and in this case they should be field variables. Example
content.add(new JLabel("Look at this"));