There are several examples on how to make a simple GUI. The question I have is what is considered the proper way of doing this, and what is the rationale of doing it either way?
I have been using Window Builder Pro under Eclipse, and examining the code that is being generated. Apparently Window Builder prefers to declare components (buttons etc.) as local variables within the main method of the visual class. However there is a button in Window Builder that allows conversion to field. Most examples that I have come across seem to prefer field declaration.
Also many examples show that it is better to create a separate class that extends JFrame. Window Builder just declares JFrame as a field in the class.
Also should I have a single handler for many events or multiple handlers. Window Builder declares anonymous handlers for each event.
I just want to be clear on what the preferred approach is.
I’d say that you only need to do this if you are going to need to refer to that component somewhere in your program. For example this is usually not the case for most garden-variety JLabels, and so these are probably best declared and used at site of use. Many JButtons and JTextComponents however will need to be used elsewhere and these will likely be best declared as private class fields.
Only if it makes sense to do so. To clarfiy, many/most quick one-off ActionListeners should be anonymous, but larger ones should be private inner classes, and complex larger ones should be separate stand-alone classes. I know of no simple test to distinguish between these other than feel and experience.
If you’re an apprentice Swing coder, you’ll probably want to put this tool to the side a bit until you are very familiar with creating Swing GUI’s, as GUI builders can be tricky to use if you’re not quite familiar with the underlying library. Otherwise if you’re a journeyman and certainly if you’re an expert Swing programmer, than sure, go ahead and continue to use it.
Most experts in the Swing field that I know suggest that it’s usually best to not extend JFrame at all, but rather to create and use a JFrame object when needed. There are several reasons for this, but number one is to avoid unintended side effects such as overriding a critical method without realizing. This has happened to me when I’ve overridden a JComponent and gave it
int getX()andint getY()methods. The component would never stay where it was supposed to be located!Most folks I know use a single handler to handle a single type of action. For instance, if you’re creating a calculator, it makes sense to create a single handler to be shared by all the number buttons, and perhaps several for the different types of operations: one handler for the basic math operations such as +, -, *, /, and one for the memory operations, and one each for more complex operations.