About Examples
This series of progressive examples shows a typical pattern for building
simple applications with a window.
- Example - First Window shows a main program that
creates an empty window (JFrame).
- Example - Second Window shows a main program
with a subclass of JPanel to build a customized GUI (Graphical
User Interface) with one
(useless) button. This is the real beginning of the pattern that will
be used in many examples in these notes.
- Example - ToUppercase is an application that
extends the above pattern to build a running program with labels,
text fields, and buttons. It's a simple application that converts strings
to uppercase, but can be the basis for many useful programs.
Rationale for some decisions
Java offers many ways to make simple programs.
Here is why I made certain choices.
- Applications, not Applets - The early hype about applets has passed,
and they haven't provided as many solutions as applications. Anyway, the
applet idea for distributed software is probably better done with Java WebStart.
By far the best single use of Java is for applications,
so the almost all examples are shown as applications.
However, the programs are organized in a way (GUI as a sublcass of JPanel)
that makes is very easy to use them as applets also.
- Subclassing JPanel - Building a GUI entirely in a static
main program may be possible, but it's not an OOP way of thinking.
Defining classes with constructors is how programming is generally
done in OOP, and these examples do that from the very beginning.
Simple, useful, realistic, examples of OOP are hard to find,
but a Graphical User Interface is an excellent example.
- Put main in separate class - The
main
method
can be put in any class.
- Students find this easier to understand.
Most students feel uncomfortable when
main
creates an object of its own class. Moving main
to its own class is simple, and makes the code easier to
understand.
- Separating
main
makes it easier to change between
an application and an applet without
confusion. It's possible to put main
in a JApplet
subclass, but again it leads
to confusion with no special advantage.
- If moves the relatively unchanging window handling code
into one place, so the student needn't worry about it.
However, there's also no problem putting main
in
any class, if you're comfortable with it.