Using JButton

A JButton generally represents a button that, when clicked by the user,
carries out a particular action. A JButton has a so-called ActionListener
attached to it, which in effect defines the task to be performed when the button
is clicked. There are generally two patterns for using a
JButton. The first is to create an individual action listener for each
button in a given window, dialog box etc. The second is to use a single action
listener for all the buttons— possibly even making the window/dialog
itself be the ActionListener. The first pattern usually looks as follows:

This pattern can obviously be a lot more succinct when you have several buttons
in your window that each perform simple tasks.

Action commands

In some cases, you might have several buttons that you want to perform the
same action. A facility called action commands can occasionally make this
easier. In this pattern, you attach a string to each button that defines
the type of action that that button is to perform when clicked. The pattern
looks as follows:

In this case, then, buttons 1 and 3 will perform the same action. Notice in the
actionPerformed() method that this is one of the few cases when we
can break the golden rule about string comparison. Normally, you should compare
strings with equals() (or equalsIgnoreCase() etc). In this particular
instance, it so happens that we know that Swing will give us back the exact same String object
that we passed to setActionCommand(). And we know that that object is a
pooled String constant. (If you're not familiar with this concept, then it
basically works like this: whenever you write a constant string in your program, all
of those constant strings with the same content will actually end up being the selfsame
String object. So although we write "EXIT" twice, there's actually only one
String object created with the text EXIT.)