The following table shows some commonly used Swing components and lists what are probably
the most useful and commonly used methods and listeners associated with those
components. Remember that we don't list certain methods that are common to all
components: for example, you can call setVisible() or setEnabled() on pretty
much any component where it'd make sense to do so.
You'll see from the above images that Swing components by default have
quite a distinct "look and feel" to them. This will make your application appear
similar on different platforms, but has the disadvantage that your apps will
look unlike other programs running on the system, and may be offputting to
users. However, you can give Swing
programs a Windows look and feel (or Mac OS L&F etc) with a simple
line of code discussed at the latter link.
Using listeners
In general, every component allows you to attach a number of listeners. A listener
is generally a special "mini class" (strictly, it's an implementation of an interface)
whose methods will get called when intersting things happen: mouse clicks, button presses etc.
When we list that a component uses a particular listener in the table above, then it means you
need to add some code such as the following:
JList l = new JList();
l.addListSelectionListener(new ListSelectionListener() {
...
});
In the part where we've put ..., you'll need to add definitions of or more methods. Which
methods you need to define depends on the particular listener. The easiest way to find out which methods
you need to add is to get your IDE to tell you. Figure 1 shows a typical case in Eclipse, for example.
When we add the addListSelectionListener() line,
a little cross appears to the left of the code (1). Clicking on this cross then gives
us the option to "Add Unimplemented Methods" (2). Eclipse then gives us some "template"
methods to fill in for that listener.

Figure 1: Using the Eclipse IDE to automatically add listener methods.
Unless otherwise stated, the Java programming articles and tutorials on this site are written by Neil Coffey.
Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles,
or if you simply have a programming question that you would like to see answered on this site. Most topics
will be considered. But in particular, the site aims to provide tutorials and information on topics that
aren't well covered elsewhere, or on Java performance information that is poorly described or understood.
Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Javamex UK 2009. All rights reserved.