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.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.