4-4 More Swing Components

Once you understand JLabel and JButton widgets (and the various approaches to event handling) you’ll find that writing code for other Swing components follows a similar pattern.  Now we’ll look at some other common Swing components, including JTextField, JCheckBox, and JComboBox.

JTextField Widgets

A JTextField component provides a box where the user can enter information.  An event occurs when the user presses the <Enter> key in the JTextField.  Event handling for JTextFields work exactly the same as with JButtons.

The JTextField class is imported on line 4, and the same ActionListener and ActionEvent classes used to handle JButton events are imported on lines 6 and 7.

Line 18 demonstrates a common way of instantiating and adding a JLabel to GUI in one step.  Since we rarely need to call a method for a JLabel widget it is not necessary to create a variable that refers to it.  You can think of this as an anonymous JLabel.

Line 21 instantiates a JTextField called userNameField and fills it with a default (“???”) starting value.  There is also a no-argument version of the constructor that you can use to leave the field blank.  Line 22 sets an approximate width of the userNameField in characters – it’s approximate because different fonts can have different widths.

The approach to event handling is essentially the same as with JButton widgets.  I’m using a regular inner class here to help keep the JTextFieldFrame constructor code more focused.  On line 37 we use the getText() method from userNameField to get the text entered by the user.  The string read does not include the <Enter> key.  Another way to get the string entered by the user is to read it from the ActionEvent object e using the getActionCommand() method (as shown on line 41).

Here is a test program:

JCheckBox Widgets

Now let’s add a check box to our GUI.  A JCheckBox component provides a small box that the user can click on to make it selected (i.e., show a check mark) or not.  JCheckBox components generate an ItemEvent (rather than an ActionEvent) and require a different event handling class called ItemListener.

The code is getting longer but there’s a pattern to it that makes it easy to follow.  Line 5 imports the JCheckBox class, and lines 9 and 10 import the necessary event handling classes for it.

On line 35 we instantiate a JCheckBox and provide some text to appear to the right of it.  The inner class for event handling follows on lines 45 to 57.  The basic form is the same as using ActionListener and ActionEvent.  However, instead of overriding the actionPerformed() method this time, we override the itemStateChanged() method.  To get the status of the JCheckBox, we call the isSelected() method on line 50.  The result of this is used to enable or disable the userNameField.  When a JTextField is disabled it becomes greyed out, the user can no longer type into it, and it no longer accepts events.

JComboBox Widgets

A JComboBox provides a drop-down list of (String) options to choose from.  This component uses the same ItemListener and ItemEvent classes as JCheckBox widgets.

Let’s look at some example code:

With Java 1.7, JComboBox became a generic class.  On line 10 I indicate that our JComboBox will contain <String> objects. On lines 11 and 12 I define two related arrays.  The first array contains the colour names (Strings) that will appear in the JComboBox.  The second array contains Color constants associated with each of the colour names.  These will be used during event handling to change the background colour of the JFrame.

Line 21 instantiates the JComboBox and passes in our array of colourNames.  Again, since JComboBox is a generic class we need to specify <String>.  You can control how many items are visible when the drop-down opens by using the setMaximumRowCount() method, as shown.

Since there is only one widget in this example, I’ve chosen to use an anonymous inner class approach for event handing.  JComboBox widgets require an ItemListener object for event handling, the same as with JCheckBox components.  On line 29 I use the getSelectedIndex() method to figure out which of the colourNames was selected and use this index to change the corresponding background colour of the JFrame.  The getContentPane() method call gives us access to the content area of the JFrame.

You Try!

  1. Write a GUI application with a JTextField where the user enters an amount of money (e.g., 23.56) and clicks a “Calculate Change” JButton.  Your program should calculate the minimum number of toonies, loonies, quarters, dimes, nickels, and pennies required and display these values in 6 uneditable JTextfield Be sure to include a descriptive JLabel beside each JTextField in your GUI.  If the user enters a negative value, your GUI should pop-up a warning dialog asking them to re-enter the amount. If the amount includes more than 2 decimal places, simply ignore (truncate) any digits beyond the second decimal place.
  2. Write an application that plays “guess the number” as follows: Your application chooses a number to be guessed by selecting a random integer in the range 1 to 1000. The program displays the following label: “I have a number between 1 and 1000. Can you guess my number?” A JTextField should be used to input the guess. As each guess is input, the background colour should change to either red or blue. Red indicates that the user is getting “warmer”, and blue indicates that the user is getting “colder”.  A JLabel should display either “Too High” or “Too Low” to help the user zero in on the correct answer. When the user gets the correct answer, “Correct!” should be displayed, and the JTextField used for input should be changed to disabled.  A JButton should be provided to allow the user to play the game again. When the JButton is clicked a new random number should be generated and the input JTextField should be enabled again.