Other Useful Swing Components

General Components

The JPasswordField Component

The JPasswordField component is a child class of JTextField and so has similar functionality, except that it masks the entered text with a character, the default mask being '*'. Figure 12.9, “A Password Field Example” shows this example running. When the text is entered (without being visible) the user can press the enter key and an ActionEvent object will be generated. This ActionEvent can be passed to the actionPerformed() method, where it can be identified and then the password field can be interrogated using getPassword() that returns an array of char. The use of the char array is for security reasons and each element of the array should be set to blank after the password has be validated. You can use the setEchoChar('X') to change the echo character to whatever is required.

Figure 12.9. A Password Field Example

A Password Field Example

The source code for this example is as below and as in JPasswordFieldExample.java

 3   // Swing JPasswordField Example - Derek Molloy
 5   import javax.swing.*;
 6   import java.awt.*; 
 7   import java.awt.event.*;
 8   import javax.swing.border.*;
10   public class JPasswordFieldExample extends JFrame implements ActionListener
11   {	
12 	JLabel l1 = new JLabel("This is a Test Swing Application");
13 	JButton b1, b2;
14 	JPasswordField pwd;
16 	public JPasswordFieldExample()
17 	{
18 		super("JPassword Field Example");
20 		JPanel p = new JPanel();
21 		p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
22 		p.setBorder(new TitledBorder("Enter Your Password:"));
24 		pwd = new JPasswordField(20);
25 		pwd.addActionListener(this);
27 		p.add(pwd);
28 		this.getContentPane().add(p);
30 		this.pack();	// set the size automatically
31 		this.show();	// display the frame
32 	}
34 	public void actionPerformed(ActionEvent e)
35 	{
36 		if (e.getSource().equals(pwd))
37 		{
38 			char[] thePassword = pwd.getPassword();
39 			String s = new String(thePassword);
40 			System.out.println("Password is " + s);
41 		}
42 	}
44 	public static void main(String[] args)
45 	{
46 		new JPasswordFieldExample();
47 	}
48   }

The JSlider Component

The JSlider component is a replacement for the Scrollbar AWT component. It is mentioned here, because there is quite a range of new functionality available with this component. For example if you look at the second JSlider object from the top (the middle one) in Figure 12.10, “A JSlider Example”, you will see that it has a title, tick marks for intervals. The code for this component is shown below:

 3   // Code for the second slider from the top.
 4   p = new JPanel();
 5   p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
 6   p.setBorder(new TitledBorder("Major Ticks"));
 8   s = new JSlider(100, 1000, 400);
 9   s.setPaintTicks(true);
10   s.setMajorTickSpacing(100);
11   s.getAccessibleContext().setAccessibleName("Major Ticks");
12   s.getAccessibleContext().setAccessibleDescription("A slider showing major tick marks");
13   s.addChangeListener(this);
14   p.add(s);
15   hp.add(p);

A JPanel object is created for each JSlider object. The layout of this JPanel object is set to BoxLayout, which allows multiple components to be laid out either vertically or horizontally, without wrapping. In this case the components are laid out in BoxLayout.Y_AXIS allowing the components to be laid out vertically, and these components will remain vertical, even when the JFrame is resized. For a BoxLayout you also have to pass the container that you wish to lay out - in this case p. TitleBorder is another border that you can use, that places a title around the border frame - in this case "Major Ticks". The JSlider object is then created with a minimum of 100, a maximum of 1000, and an initial value of 400. The setPaintTicks() enables/disables the tick lines below the JSlider component. The setMajorTickSpacing(100) method call sets spacing to 100, so we will have 10 ticks in this case.

The next two lines demonstrate the Accessibility API (part of the JFCs) that sets the Accessible name of this component to "Major Ticks" and the description to "A slider showing major tick marks", so that if the user has a visual disability that speech synthesis software would be capable of indentifying the reason for the component to allow that person to use it.

Figure 12.10. A JSlider Example

A JSlider Example

Other constructors that can be used with JSlider are:

          Creates a horizontal slider with the range 0 to 100 and an initial value of 50. 
  JSlider(BoundedRangeModel brm)
          Creates a horizontal slider using the specified BoundedRangeModel. A
          BoundedRangeModel defines the data model used by components like 
          sliders and progressBars, four interrelated integer properties: minimum, maximum, 
          extent and value. These four integers define two nested ranges like this: 
		    minimum <= value <= value+extent <= maximum
  JSlider(int orientation) 
          Creates a slider using the specified orientation with the range 0 to 100 and an 
          initial value of 50. 
  JSlider(int min, int max) 
          Creates a horizontal slider using the specified min and max with an initial value equal 
          to the average of the min plus max. 
  JSlider(int min, int max, int value)  
          Creates a horizontal slider using the specified min, max and value. The one used here.
  JSlider(int orientation, int min, int max, int value) 
          Creates a slider with the specified orientation and the specified minimum, 
          maximum, and initial values. 

The Full code for this example can be seen in JSliderExample.java

The JProgressBar Component

A JProgressBar component displays an Integer value within a bounded interval. A progress bar typically communicates the progress of an event by displaying its percentage of completion and possibly also provides a textual description. See Figure 12.11, “A JProgressBar Example” for a basic example.

Figure 12.11. A JProgressBar Example

A JProgressBar Example

The code for this is in JProgressBarExample.java There are several constructors for JProgressBar:

      Creates a horizontal progress bar that displays a border but no progress string. 
  JProgressBar(BoundedRangeModel newModel)
      Creates a horizontal progress bar that uses the specified model to hold the progress bar's data. 
  JProgressBar(int orient)
      Creates a progress bar with the specified orientation, which can be either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL. 
  JProgressBar(int min, int max)
      Creates a horizontal progress bar with the specified minimum and maximum. 
  JProgressBar(int orient, int min, int max)
      Creates a progress bar using the specified orientation, minimum, and maximum. 

You can set the value of the progress bar by using the setValue(int) method and you can get the value by using the getValue() method.

The JToggleButton Component

The JToggleButton component is very similar to a checkbox, in that it can be selected or not selected. Figure 12.12, “The JToggleButton component example (a) selected (b) not selected.” shows a selected JToggleButton object and a non-selected component. It is very similar to the JButton class except that it can have two states.

Figure 12.12. The JToggleButton component example (a) selected (b) not selected.

The JToggleButton component example (a) selected (b) not selected.The JToggleButton component example (a) selected (b) not selected.

The code for this example is in JToggleButtonExample.java There are several constructors for a JToggleButton:

          Creates an initially unselected toggle button without setting the text or image. 
  JToggleButton(Action a) 
          Creates a toggle button where properties are taken from the Action supplied. 
  JToggleButton(Icon icon) 
          Creates an initially unselected toggle button with the specified image but no text. 
  JToggleButton(Icon icon, boolean selected) 
          Creates a toggle button with the specified image and selection state, but no text. 
  JToggleButton(String text) 
          Creates an unselected toggle button with the specified text. 
  JToggleButton(String text, boolean selected) 
          Creates a toggle button with the specified text and selection state. 
  JToggleButton(String text, Icon icon) 
          Creates a toggle button that has the specified text and image, and that is initially unselected. 
  JToggleButton(String text, Icon icon, boolean selected) 
          Creates a toggle button with the specified text, image, and selection state. 

If you wish to find the current state of the JToggleButton object using the isSelected() method that returns a boolean value.

Exercise. Write an Egg Timer

Task: Write an egg timer Swing application that counts to two minutes (well for runny eggs), updating the time as a progress bar and playing a sound when it is finished. You should be able to stop the timer at any stage using the "stop" button. My version is in Figure 12.13, “The Egg Timer Exercise”. You can use this sound ready.wav if you wish.

Figure 12.13. The Egg Timer Exercise

The Egg Timer Exercise

Hints: Don't set the delay to 1 second until you have finished, otherwise you will have to wait a full two minutes every time you are debugging your application. To load a sound clip in an application you have to use something like:

 3   File f = new File("ready.wav");
 4   AudioClip theSound;
 5   try {
 6     theSound = Applet.newAudioClip(f.toURL());
 7   } 
 8   catch (java.net.MalformedURLException e) {
 9     theSound = null;
10     System.out.println("Exception " + e.toString());
11   }
12   if (this.theSound != null) {
13     this.theSound.play();
14   }

And this involves importing the java.applet.* package and the java.io.* package. You may also (depending on the way you write your code) have to add a sleep call after you call the play() method of the AudioClip as the application/function may finish before the sound clip has played completely.

Solution: My solution is here - EggTimerApplication.java. Once again have a good attempt at the exercise before reading my solution (as yours may be better!).