java.awt.Color
). Generally the
Swing component class names start with "J" and the AWT ones don't,
e.g. JButton
vs. Button
.For example, see the class heirarchy for JCheckBox
In fact the Motif and Win32 APIs both have very OO "feel" to them although
they are implemented in non OO languages. MFC puts an OO interface to Win32
which shares many concepts with Swing.
Swing is written in Java and so it's a lot easier to implement as an OO
design.
For example, the model for an on/off switch might be as simple as a boolean variable, displayed as a checkbox, and controlled by the user clicking the check-box on and off. In practise, the distinction between view and control is not often made - they're generally the same thing in Swing. The important separation is between data and UI. From now on I'll just refer to model and view.
xxxxModel
s
(e.g. ListModel
, TreeModel
) and many classes which
attach to a model to produce a view of it (e.g. JList
,
JTree
).TreeModel
? - It's an interface, so in order to make
your class be a model for a tree view, you just implement
TreeModel
. There's nothing to stop you implementing more than
one interface, e.g. in Apu the data is held in a class which implements
TreeModel
and TableModel
. What kind of
methods do you think you might find in the TreeModel
interface?xxxxModel
interfaces,
e.g. DefaultTreeModel
.
JTree(TreeModel newModel)
, or using a "set" method,
e.g. JTree.setModel(TreeModel newModel)
TreeModel
) will keep a list of all the
"listeners" who are interested in it, and so whenever the data in the model
changes, it can work through the list and tell each listener that it may need
to repaint itselfTreeModel
method
which adds a new listener? It's a TreeModelListener
, which is an
interface, and the interface for TreeModelListener
contains
methods such as treeNodesRemoved()
,
treeStructureChanged()
. So you may well find that when you write
a class which is can display a view of a Tree, that class will be declared as
implements TreeModelListener
.
If you use a layout manager, you can tell Swing how you want your components arranged, and leave it to work out what things should look like when the window changes size. For example, you might say that you want a label on the left of the window, and a text field to its right, and that as the window gets wider, the label stays the same width while the text field expands.
import javax.swing.*; public class Swing1 { public static void main(String[] args) { if (args.length == 0) { System.out.println("please give me some arguments"); return; } JFrame frame = new JFrame("Swing1"); JPanel panel = new JPanel(); for (int i=0; i<args.length; i++) { JButton button = new JButton(args[i]); panel.add(button); } frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
DefaultButtonModel
object and make it be the model
for all the buttons that the program creates. What do you think will happen
now? Try it and see.