9.2 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 9.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 9.9. A Password Field Example


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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
/** Java Swing Examples - Written by Derek Molloy, Dublin City University, Ireland
* see: http://ee402.eeng.dcu.ie/
*/

package ee402;

import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;

@SuppressWarnings("serial")
public class JPasswordFieldExample extends JFrame implements ActionListener {        
        JLabel l1 = new JLabel("This is a Test Swing Application");
        JButton b1, b2;
        JPasswordField pwd;
        
        public JPasswordFieldExample()
        {
                super("JPassword Field Example");

                JPanel p = new JPanel();
                p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
                p.setBorder(new TitledBorder("Enter Your Password:"));

                pwd = new JPasswordField(20);
                pwd.addActionListener(this);
        
                p.add(pwd);
                this.getContentPane().add(p);

                this.pack();        // set the size automatically
                this.setVisible(true);
        }
        
        public void actionPerformed(ActionEvent e)
        {
                if (e.getSource().equals(pwd))
                {
                        char[] thePassword = pwd.getPassword();
                        String s = new String(thePassword);
                        System.out.println("Password is " + s);
                }
        }
        
        public static void main(String[] args)
        {
                new JPasswordFieldExample();
        }
}

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 9.10, “A JSlider Example”, you will see that it has a title, tick marks for intervals. The code for this component is shown below:

343536373839404142434445
                // Slider 2
                p = new JPanel();
                p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
                p.setBorder(new TitledBorder("Major Ticks"));
                s = new JSlider(100, 1000, 400);
                s.setPaintTicks(true);
                s.setMajorTickSpacing(100);
                s.getAccessibleContext().setAccessibleName("Major Ticks");
                s.getAccessibleContext().setAccessibleDescription("A slider showing major tick marks");
                //s.addChangeListener(this);
                p.add(s);
                hp.add(p);

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 pTitleBorder 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 identifying the reason for the component to allow that person to use it.

Figure 9.10. JSlider Example


Other constructors that can be used with JSlider are:

Constructors 
Constructor and Description
JSlider()
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.
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.
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

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 9.11, “A JProgressBar Example” for a basic example.

Figure 9.11. A JProgressBar Example


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

Constructors 
Constructor and Description
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 SwingConstants.VERTICAL or SwingConstants.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 9.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 9.12. 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:

Constructors 
Constructor and Description
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 9.13, “The Egg Timer Exercise”. You can use this sound ready.wav if you wish.

Figure 9.13. 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:

                URL clipLocation = this.getClass().getResource("ready.wav");
                AudioClip theSound = Applet.newAudioClip(clipLocation);
and to play:
                theSound.play();

And this involves importing the java.applet.* 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!).



These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
Comments