Making Choices

   

Core Java™ 2: Volume I - Fundamentals
By Cay S. Horstmann, Gary Cornell
Table of Contents
Chapter 9.  User Interface Components with Swing


You now know how to collect text input from users, but there are many occasions where you would rather give users a finite set of choices than have them enter the data in a text component. Using a set of buttons or a list of items tells your users what choices they have. (It also saves you the trouble of error checking.) In this section, you will learn how to program check boxes, radio buttons, lists of choices, and sliders.

Check Boxes

If you want to collect just a "yes" or "no" input, use a check box component. Check boxes automatically come with labels that identify them. The user usually checks the box by clicking inside it, and turns off the check mark by clicking inside the box again. To toggle the check mark, the user can also press the space bar when the focus is in the check box.

Figure 9-16 shows a simple program with two check boxes, one to turn on or off the italic attribute of a font, and the other for boldface. Note that the second check box has focus, as indicated by the rectangle around the label. Each time the user clicks one of the check boxes, we refresh the screen, using the new font attributes.

Figure 9-16. Check boxes

graphics/09fig16.gif

Check boxes need a label next to them to identify their purpose. You give the label text in the constructor.

 bold = new JCheckBox("Bold"); 

You use the setSelected method to turn a check box on or off. For example,

 bold.setSelected(true); 

The isSelected method then retrieves the current state of each check box. It is false if unchecked; true if checked.

When the user clicks on a check box, this triggers an action event. As always, you attach an action listener. In our program, the two buttons share the same action listener.

 ActionListener listener = . . . bold.addActionListener(listener); italic.addActionListener(listener); 

Its actionPerformed method queries the state of the bold and italic check boxes and sets the font of the panel to plain, bold, italic, or both.

 public void actionPerformed(ActionEvent event) {    int mode = 0;    if (bold.isSelected()) mode += Font.BOLD;    if (italic.isSelected()) mode += Font.ITALIC;    label.setFont(new Font("Serif", mode, FONTSIZE)); } 

Example 9-6 is the complete program listing for the check box example.

graphics/notes_icon.gif

In AWT, the equivalent component to a JCheckBox is called a Checkbox (with a lowercase "b"). It generates item events, not action events.

Example 9-6 CheckBoxTest.java
  1. import java.awt.*;  2. import java.awt.event.*;  3. import javax.swing.*;  4.  5. public class CheckBoxTest  6. {  7.    public static void main(String[] args)  8.    {  9.       CheckBoxFrame frame = new CheckBoxFrame(); 10.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11.       frame.show(); 12.    } 13. } 14. 15. /** 16.    A frame with a sample text label and check boxes for 17.    selecting font attributes. 18. */ 19. class CheckBoxFrame extends JFrame 20. { 21.    public CheckBoxFrame() 22.    { 23.       setTitle("CheckBoxTest"); 24.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 25. 26.       Container contentPane = getContentPane(); 27. 28.       // add the sample text label 29. 30.       label = new JLabel( 31.          "The quick brown fox jumps over the lazy dog."); 32.       label.setFont(new Font("Serif", Font.PLAIN, FONTSIZE)); 33.       contentPane.add(label, BorderLayout.CENTER); 34. 35.       // this listener sets the font attribute of 36.       // the label to the check box state 37. 38.       ActionListener listener = new 39.          ActionListener() 40.          { 41.             public void actionPerformed(ActionEvent event) 42.             { 43.                int mode = 0; 44.                if (bold.isSelected()) mode += Font.BOLD; 45.                if (italic.isSelected()) mode += Font.ITALIC; 46.                label.setFont(new Font("Serif", mode, FONTSIZE)); 47.             } 48.          }; 49. 50.       // add the check boxes 51. 52.       JPanel buttonPanel = new JPanel(); 53. 54.       bold = new JCheckBox("Bold"); 55.       bold.addActionListener(listener); 56.       buttonPanel.add(bold); 57. 58.       italic = new JCheckBox("Italic"); 59.       italic.addActionListener(listener); 60.       buttonPanel.add(italic); 61. 62.       contentPane.add(buttonPanel, BorderLayout.SOUTH); 63.    } 64. 65.    public static final int DEFAULT_WIDTH = 300; 66.    public static final int DEFAULT_HEIGHT = 200; 67. 68.    private JLabel label; 69.    private JCheckBox bold; 70.    private JCheckBox italic; 71. 72.    private static final int FONTSIZE = 12; 73. } 

javax.swing.JCheckBox 1.2

graphics/api_icon.gif
  • JCheckBox(String label)

    Parameters:

    label

    The label on the check box

  • JCheckBox(String label, boolean state)

    Parameters:

    label

    The label on the check box

     

    state

    The initial state of the check box

  • JCheckBox(String label, Icon icon)

    constructs a check box that is initially unselected.

    Parameters:

    label

    The label on the check box

     

    icon

    The icon on the check box

  • boolean isSelected ()

    returns the state of the check box.

  • void setSelected(boolean state)

    sets the check box to a new state.

Radio Buttons

In the previous example, the user could check either, both, or none of the two check boxes. In many cases, we want to require the user to check only one of several boxes. When another box is checked, the previous box is automatically unchecked. Such a group of boxes is often called a radio button group because the buttons work like the station selector buttons on a radio. When you push in one button, the previously depressed button pops out. Figure 9-17 shows a typical example. We allow the user to select a font size among the choices Small, Medium, Large, and Extra large but, of course, we will allow the user to select only one size at a time.

Figure 9-17. A radio button group

graphics/09fig17.gif

Implementing radio button groups is easy in Swing. You construct one object of type ButtonGroup for every group of buttons. Then, you add objects of type JRadioButton to the button group. The button group object is responsible for turning off the previously set button when a new button is clicked.

 ButtonGroup group = new ButtonGroup(); JRadioButton smallButton    = new JRadioButton("Small", false); group.add(smallButton); JRadioButton mediumButton    = new JRadioButton("Medium", true); group.add(mediumButton); . . . 

The second argument of the constructor is true for the button that should be checked initially, and false for all others. Note that the button group controls only the behavior of the buttons; if you want to group the buttons together for layout purposes, you also need to add them to a container such as a JPanel.

If you look again at Figures 9-16 and 9-17, you will note that the appearance of the radio buttons is different from check boxes. Check boxes are square and contain a check mark when selected. Radio buttons are round and contain a dot when selected.

The event notification mechanism for radio buttons is the same as for any other buttons. When the user checks a radio button, the radio button generates an action event. In our example program, we define an action listener that sets the font size to a particular value:

 ActionListener listener = new    ActionListener()    {       public void actionPerformed(ActionEvent evt)       {          // size refers to the final parameter of the          // addRadioButton method          label.setFont(new Font("Serif", Font.PLAIN,             size));       }    }; 

Compare this listener set-up with that of the check box example. Each radio button gets a different listener object. Each listener object knows exactly what it needs to do set the font size to a particular value. In the case of the check boxes, we used a different approach. Both check boxes have the same action listener. It called a method that looked at the current state of both check boxes.

Could we follow the same approach here? We could have a single listener that computes the size as follows:

 if (smallButton.isSelected()) size = 8; else if (mediumButton.isSelected()) size = 12; . . . 

However, we prefer to use separate action listener objects because they tie the size values more closely to the buttons.

graphics/notes_icon.gif

If you have a group of radio buttons, you know that only one of them is selected. It would be nice to be able to quickly find out which one, without having to query all the buttons in the group. Since the ButtonGroup object controls all buttons, it would be convenient if this object could give us a reference to the selected button. Indeed, the ButtonGroup class has a getSelection method, but that method doesn't return the radio button that is selected. Instead, it returns a ButtonModel reference to the model attached to the button. Unfortunately, none of the ButtonModel methods are very helpful. The ButtonModel interface inherits a method getSelectedObjects from the ItemSelectable interface that, rather uselessly, returns null. The getActionCommand method looks promising because the "action command" of a radio button is its text label. But the action command of its model is null. Only if you explicitly set the action commands of all radio buttons with the setActionCommand method do the models' action command values also get set. Then you can retrieve the action command of the currently selected button with buttonGroup.getSelection().getActionCommand().

Example 9-7 is the complete program for font size selection that puts a set of radio buttons to work.

Example 9-7 RadioButtonTest.java
  1. import java.awt.*;  2. import java.awt.event.*;  3. import javax.swing.*;  4.  5. public class RadioButtonTest  6. {  7.    public static void main(String[] args)  8.    {  9.       RadioButtonFrame frame = new RadioButtonFrame(); 10.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11.       frame.show(); 12.    } 13. } 14. 15. /** 16.    A frame with a sample text label and radio buttons for 17.    selecting font sizes. 18. */ 19. class RadioButtonFrame extends JFrame 20. { 21.    public RadioButtonFrame() 22.    { 23.       setTitle("RadioButtonTest"); 24.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 25. 26.       Container contentPane = getContentPane(); 27. 28.       // add the sample text label 29. 30.       label = new JLabel( 31.          "The quick brown fox jumps over the lazy dog."); 32.       label.setFont(new Font("Serif", Font.PLAIN, 33.          DEFAULT_SIZE)); 34.       contentPane.add(label, BorderLayout.CENTER); 35. 36.       // add the radio buttons 37. 38.       buttonPanel = new JPanel(); 39.       group = new ButtonGroup(); 40. 41.       addRadioButton("Small", 8); 42.       addRadioButton("Medium", 12); 43.       addRadioButton("Large", 18); 44.       addRadioButton("Extra large", 36); 45. 46.       contentPane.add(buttonPanel, BorderLayout.SOUTH); 47.    } 48. 49.    /** 50.       Adds a radio button that sets the font size of the 51.       sample text. 52.       @param name the string to appear on the button 53.       @param size the font size that this button sets 54.    */ 55.    public void addRadioButton(String name, final int size) 56.    { 57.       boolean selected = size == DEFAULT_SIZE; 58.       JRadioButton button = new JRadioButton(name, selected); 59.       group.add(button); 60.       buttonPanel.add(button); 61. 62.       // this listener sets the label font size 63. 64.       ActionListener listener = new 65.          ActionListener() 66.          { 67.             public void actionPerformed(ActionEvent evt) 68.             { 69.                // size refers to the final parameter of the 70.                // addRadioButton method 71.                label.setFont(new Font("Serif", Font.PLAIN, 72.                   size)); 73.             } 74.          }; 75. 76.       button.addActionListener(listener); 77.    } 78. 79.    public static final int DEFAULT_WIDTH = 400; 80.    public static final int DEFAULT_HEIGHT = 200; 81. 82.    private JPanel buttonPanel; 83.    private ButtonGroup group; 84.    private JLabel label; 85. 86.    private static final int DEFAULT_SIZE = 12; 87. } 

javax.swing.JRadioButton 1.2

graphics/api_icon.gif
  • JRadioButton(String label, boolean state)

    Parameters:

    label

    The label on the check box

     

    state

    The initial state of the check box

  • JRadioButton(String label, Icon icon)

    constructs a radio button that is initially unselected.

    Parameters:

    label

    The label on the radio button

     

    icon

    The icon on the radio button

javax.swing.ButtonGroup 1.2

graphics/api_icon.gif
  • void add(AbstractButton b)

    adds the button to the group.

  • ButtonModel getSelection()

    returns the button model of the selected button.

javax.swing.ButtonModel 1.2

graphics/api_icon.gif
  • String getActionCommand()

    returns the action command for this button model.

javax.swing.AbstractButton 1.2

graphics/api_icon.gif
  • void setActionCommand(String s)

    sets the action command for this button and its model.

Borders

If you have multiple groups of radio buttons in a window, you will want to visually indicate which buttons are grouped together. The Swing set provides a set of useful borders for this purpose. You can apply a border to any component that extends JComponent. The most common usage is to place a border around a panel and fill that panel with other user interface elements such as radio buttons.

There are quite a few borders to choose from, but you follow the same steps for all of them.

  1. Call a static method of the BorderFactory to create a border. You can choose among the following styles (see Figure 9-18):

    • Lowered bevel

    • Raised bevel

    • Etched

    • Line

    • Matte

    • Empty (just to create some blank space around the component)

    Figure 9-18. Testing border types

    graphics/09fig18.gif

  2. If you like, add a title to your border by passing your border to BorderFactory.createTitledBorder.

  3. If you really want to go all out, combine several borders with a call to BorderFactory.createCompoundBorder.

  4. Add the resulting border to your component by calling the setBorder method of the JComponent class.

For example, here is how you add an etched border with a title to a panel:

 Border etched = BorderFactory.createEtchedBorder() Border titled = BorderFactory.createTitledBorder(etched,    "A Title"); panel.setBorder(titled); 

Run the program in Example 9-8 to get an idea what the various borders look like.

The various borders have different options for setting border widths and colors. See the API notes for details. True border enthusiasts will appreciate that there is also a SoftBevelBorder class for beveled borders with softened corners, and that a LineBorder can have rounded corners as well. These borders can be constructed only by using one of the class constructors there is no BorderFactory method for them.

Example 9-8 BorderTest.java
  1. import java.awt.*;  2. import java.awt.event.*;  3. import javax.swing.*;  4. import javax.swing.border.*;  5.  6. public class BorderTest  7. {  8.    public static void main(String[] args)  9.    { 10.       BorderFrame frame = new BorderFrame(); 11.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12.       frame.show(); 13.    } 14. } 15. 16. /** 17.    A frame with radio buttons to pick a border style. 18. */ 19. class BorderFrame extends JFrame 20. { 21.    public BorderFrame() 22.    { 23.       setTitle("BorderTest"); 24.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 25. 26.       demoPanel = new JPanel(); 27.       buttonPanel = new JPanel(); 28.       group = new ButtonGroup(); 29. 30.       addRadioButton("Lowered bevel", 31.          BorderFactory.createLoweredBevelBorder()); 32.       addRadioButton("Raised bevel", 33.          BorderFactory.createRaisedBevelBorder()); 34.       addRadioButton("Etched", 35.          BorderFactory.createEtchedBorder()); 36.       addRadioButton("Line", 37.          BorderFactory.createLineBorder(Color.BLUE)); 38.       addRadioButton("Matte", 39.          BorderFactory.createMatteBorder( 40.             10, 10, 10, 10, Color.BLUE)); 41.       addRadioButton("Empty", 42.          BorderFactory.createEmptyBorder()); 43. 44.       Border etched = BorderFactory.createEtchedBorder(); 45.       Border titled = BorderFactory.createTitledBorder 46.          (etched, "Border types"); 47.       buttonPanel.setBorder(titled); 48. 49.       Container contentPane = getContentPane(); 50. 51.       contentPane.setLayout(new GridLayout(2, 1)); 52.       contentPane.add(buttonPanel); 53.       contentPane.add(demoPanel); 54.    } 55. 56.    public void addRadioButton(String buttonName, final Border b) 57.    { 58.       JRadioButton button = new JRadioButton(buttonName); 59.       button.addActionListener(new 60.          ActionListener() 61.          { 62.             public void actionPerformed(ActionEvent event) 63.             { 64.                demoPanel.setBorder(b); 65.                validate(); 66.             } 67.          }); 68.       group.add(button); 69.       buttonPanel.add(button); 70.    } 71. 72.    public static final int DEFAULT_WIDTH = 600; 73.    public static final int DEFAULT_HEIGHT = 200; 74. 75.    private JPanel demoPanel; 76.    private JPanel buttonPanel; 77.    private ButtonGroup group; 78. } 

javax.swing.BorderFactory 1.2

graphics/api_icon.gif
  • static Border createLineBorder(Color color)

  • static Border createLineBorder(Color color, int thickness)

    create a simple line border.

  • static MatteBorder createMatteBorder(int top, int left, int bottom, int right, Color color)

  • static MatteBorder createMatteBorder(int top, int left, int bottom, int right, Icon tileIcon)

    create a thick border that is filled with a color or a repeating icon.

  • static Border createEmptyBorder()

  • static Border createEmptyBorder(int top, int left, int bottom, int right)

    create an empty border.

  • static Border createEtchedBorder()

  • static Border createEtchedBorder(Color highlight, Color shadow)

  • static Border createEtchedBorder(int type)

  • static Border createEtchedBorder(int type, Color highlight, Color shadow)

    create a line border with a 3D effect.

    Parameters:

    highlight, shadow

    Colors for 3D effect

     

    type

    One of EtchedBorder.RAISED, EtchedBorder.LOWERED

  • static Border createBevelBorder(int type)

  • static Border createBevelBorder(int type, Color highlight, Color shadow)

  • static Border createLoweredBevelBorder()

  • static Border createRaisedBevelBorder()

    create a border that gives the effect of a lowered or raised surface.

    Parameters:

    type

    One of BevelBorder.LOWERED, BevelBorder.RAISED

     

    highlight, shadow

    Colors for 3D effect

  • static TitledBorder createTitledBorder(String title)

  • static TitledBorder createTitledBorder(Border border)

  • static TitledBorder createTitledBorder(Border border, String title)

  • static TitledBorder createTitledBorder(Border border, String title, int justification, int position)

  • static TitledBorder createTitledBorder(Border border, String title, int justification, int position, Font font)

  • static TitledBorder createTitledBorder(Border border, String title, int justification, int position, Font font, Color color)

    Parameters:

    title

    The title string

     

    border

    The border to decorate with the title

     

    justification

    One of TitledBorder.LEFT, TitledBorder.CENTER, TitledBorder.RIGHT

     

    position

    One of the TitledBorder constants ABOVE_TOP, TOP, BELOW_TOP, ABOVE_BOTTOM, BOTTOM, BELOW_BOTTOM

     

    font

    The font for the title

     

    color

    The color of the title

  • static CompoundBorder createCompoundBorder(Border outsideBorder, Border insideBorder)

    combines two borders to a new border.

javax.swing.border.SoftBevelBorder 1.2

graphics/api_icon.gif
  • SoftBevelBorder(int type)

  • SoftBevelBorder(int type, Color highlight, Color shadow)

    create a bevel border with softened corners.

    Parameters:

    type

    One of BevelBorder.LOWERED, BevelBorder.RAISED

     

    color, shadow

    Colors for 3D effect

javax.swing.border.LineBorder 1.2

graphics/api_icon.gif
  • public LineBorder(Color color, int thickness, boolean roundedCorners)

    creates a line border with the given color and thickness. If roundedCorners is true, the border has rounded corners.

javax.swing.JComponent 1.2

graphics/api_icon.gif
  • void setBorder(Border border)

    sets the border of this component.

Combo Boxes

If you have more than a handful of alternatives, radio buttons are not a good choice because they take up too much screen space. Instead, you can use a combo box. When the user clicks on the component, a list of choices drops down, and the user can then select one of them (see Figure 9-19).

Figure 9-19. A combo box

graphics/09fig19.gif

If the drop-down list box is set to be editable, then you can edit the current selection as if it was a text field. For that reason, this component is called a combo box it combines the flexibility of an edit box with a set of predefined choices. The JComboBox class provides a combo box component.

You call the setEditable method to make the combo box editable. Note that editing affects only the current item. It does not change the contents of the list.

You can obtain the current selection or edited text by calling the getSelectedItem method.

In the example program, the user can choose a font style from a list of styles (Serif, SansSerif, Monospaced, etc.). The user can also type in another font.

You add the choice items with the addItem method. In our program, addItem is called only in the constructor, but you can call it any time.

 faceCombo = new JComboBox(); faceCombo.setEditable(true); faceCombo.addItem("Serif"); faceCombo.addItem("SansSerif"); . . . 

This method adds the string at the end of the list. You can add new items anywhere in the list with the insertItemAt method:

 faceCombo.insertItemAt("Monospaced", 0); // add at the beginning 

You can add items of any type the combo box invokes each item's toString method to display it.

If you need to remove items at run time, you use the removeItem or removeItemAt method, depending on whether you supply the item to be removed or its position.

 faceCombo.removeItem("Monospaced"); faceCombo.removeItemAt(0); // remove first item 

There is also a removeAllItems method to remove all items at once.

When the user selects an item from a combo box, the combo box generates an action event. To find out which item was selected, call getSource on the event parameter to get a reference to the combo box that sent the event. Then call the getSelectedItem method to retrieve the currently selected item. You need to cast the returned value to the appropriate type, usually String.

 public void actionPerformed(ActionEvent event) {    label.setFont(new Font(       (String)faceCombo.getSelectedItem(),       Font.PLAIN,       DEFAULT_SIZE)); } 

Example 9-9 shows the complete program.

Example 9-9 ComboBoxTest.java
  1. import java.awt.*;  2. import java.awt.event.*;  3. import javax.swing.*;  4.  5. public class ComboBoxTest  6. {  7.    public static void main(String[] args)  8.    {  9.       ComboBoxFrame frame = new ComboBoxFrame(); 10.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11.       frame.show(); 12.    } 13. } 14. 15. /** 16.    A frame with a sample text label and a combo box for 17.    selecting font faces. 18. */ 19. class ComboBoxFrame extends JFrame 20. { 21.    public ComboBoxFrame() 22.    { 23.       setTitle("ComboBoxTest"); 24.       setSize(WIDTH, HEIGHT); 25. 26.       Container contentPane = getContentPane(); 27. 28.       // add the sample text label 29. 30.       label = new JLabel( 31.          "The quick brown fox jumps over the lazy dog."); 32.       label.setFont(new Font("Serif", Font.PLAIN, 33.          DEFAULT_SIZE)); 34.       contentPane.add(label, BorderLayout.CENTER); 35. 36.       // make a combo box and add face names 37. 38.       faceCombo = new JComboBox(); 39.       faceCombo.setEditable(true); 40.       faceCombo.addItem("Serif"); 41.       faceCombo.addItem("SansSerif"); 42.       faceCombo.addItem("Monospaced"); 43.       faceCombo.addItem("Dialog"); 44.       faceCombo.addItem("DialogInput"); 45. 46.       // the combo box listener changes the label font to the 47.       // selected face name 48. 49.       faceCombo.addActionListener(new 50.          ActionListener() 51.          { 52.             public void actionPerformed(ActionEvent event) 53.             { 54.                label.setFont(new Font( 55.                   (String)faceCombo.getSelectedItem(), 56.                   Font.PLAIN, 57.                   DEFAULT_SIZE)); 58.             } 59.          }); 60. 61.       // add combo box to a panel at the frame's southern border 62. 63.       JPanel comboPanel = new JPanel(); 64.       comboPanel.add(faceCombo); 65.       contentPane.add(comboPanel, BorderLayout.SOUTH); 66.    } 67. 68.    public static final int WIDTH = 300; 69.    public static final int HEIGHT = 200; 70. 71.    private JComboBox faceCombo; 72.    private JLabel label; 73.    private static final int DEFAULT_SIZE = 12; 74. } 

javax.swing.JComboBox 1.2

graphics/api_icon.gif
  • void setEditable(boolean b)

    Parameters:

    b

    true if the combo box field can be edited by the user, false otherwise

  • void addItem(Object item)

    adds an item to the item list.

  • void insertItemAt(Object item, int index)

    inserts an item into the item list at a given index.

  • void removeItem(Object item)

    removes an item from the item list.

  • void removeItemAt(int index)

    removes the item at an index.

  • void removeAllItems()

    removes all items from the item list.

  • Object getSelectedItem()

    returns the currently selected item.

Sliders

Combo boxes let users choose from a discrete set of values. Sliders offer a choice from a continuum of values, for example, any number between 1 and 100.

The most common way of constructing a slider is as follows:

 JSlider slider = new JSlider(min, max, initialValue); 

If you omit the minimum, maximum, and initial values, they are initialized with 0, 100, and 50, respectively.

Or, if you want the slider to be vertical, then use the following constructor call:

 JSlider slider = new JSlider(SwingConstants.VERTICAL,    min, max, initialValue); 

These constructors create a plain slider, such as the top slider in Figure 9-20. You will see presently how to add decorations to a slider.

Figure 9-20. Sliders

graphics/09fig20.gif

As the user slides the slider bar, the value of the slider moves between the minimum and the maximum values. When the value changes, a ChangeEvent is sent to all change listeners. To be notified of the change, you need to call the addChangeListener method and install an object that implements the ChangeListener interface. That interface has a single method, stateChanged. In that method, you should retrieve the slider value:

 public void stateChanged(ChangeEvent event) {    JSlider slider = (JSlider)event.getSource();    int value = slider.getValue();    . . . } 

You can embellish the slider by showing ticks. For example, in the sample program, the second slider uses the following settings:

 slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); 

The slider is decorated with large tick marks every 20 units and small tick marks every 5 units. The units refer to slider values, not pixels.

These instructions only set the units for the tick marks. To actually have the tick marks appear, you also need to call

 slider.setPaintTicks(true); 

The major and minor tick marks are independent. For example, you can set major tick marks every 20 units and minor tick marks every 7 units, but you'll get a very messy scale.

You can force the slider to snap to ticks. Whenever the user has finished dragging a slider in snap mode, it is immediately moved to the closest tick. You activate this mode with the call

 slider.setSnapToTicks(true); 

graphics/notes_icon.gif

The "snap to ticks" behavior doesn't work as well as you might imagine. Until the slider has actually snapped, the change listener still reports slider values that don't correspond to ticks. And if you click next to the slider an action that normally advances the slider a bit in the direction of the click a slider with "snap to ticks" does not move to the next tick.

You can ask for tick mark labels for the major tick marks, by calling

 slider.setPaintLabels(true); 

For example, with a slider ranging from 0 to 100 and major tick spacing of 20, the ticks are labeled 0, 20, 40, 60, 80, and 100.

You can also supply other tick marks, such as strings or icons (see Figure 9-20). The process is a bit convoluted. You need to fill a hash table with keys new Integer(tickValue) and values of type Component. Then you call the setLabelTable method. The components are placed under the tick marks. Usually, you use JLabel objects. Here is how you can label ticks as A, B, C, D, E, and F.

 Hashtable labelTable = new Hashtable(); labelTable.put(new Integer(0), new JLabel("A")); labelTable.put(new Integer(20), new JLabel("B")); . . . labelTable.put(new Integer(100), new JLabel("F")); slider.setLabelTable(labelTable); 

See Chapter 2 of Volume 2 for more information about hash tables.

Example 9-10 also shows a slider with icons as tick labels.

graphics/exclamatory_icon.gif

If your tick marks or labels don't show, double-check that you called setPaintTicks(true) and setPaintLabels(true).

Finally, if you use the Metal look and feel, you can add a visual enhancement to your sliders and have the portion from the minimum value to the current value "filled in." The fourth and fifth sliders in Figure 9-20 are filled. You fill a slider by setting a client property as follows:

 slider.putClientProperty("JSlider.isFilled", Boolean.TRUE); 

The fifth slider has its direction reversed by calling

 slider.setInverted(true); 

The example program shows all these visual effects with a collection of sliders. Each slider has a change event listener installed that places the current slider value into the text field at the bottom of the frame.

Example 9-10 SliderTest.java
   1. import java.awt.*;   2. import java.awt.event.*;   3. import java.util.*;   4. import javax.swing.*;   5. import javax.swing.event.*;   6.   7. public class SliderTest   8. {   9.    public static void main(String[] args)  10.    {  11.       SliderTestFrame frame = new SliderTestFrame();  12.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  13.       frame.show();  14.    }  15. }  16.  17. /**  18.    A frame with many sliders and a text field to show slider  19.    values.  20. */  21. class SliderTestFrame extends JFrame  22. {  23.    public SliderTestFrame()  24.    {  25.       setTitle("SliderTest");  26.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);  27.  28.       sliderPanel = new JPanel();  29.       sliderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));  30.  31.       // common listener for all sliders  32.       listener = new  33.          ChangeListener()  34.          {  35.             public void stateChanged(ChangeEvent event)  36.             {  37.                // update text field when the slider value changes  38.                JSlider source = (JSlider)event.getSource();  39.                textField.setText("" + source.getValue());  40.             }  41.          };  42.  43.       // add a plain slider  44.  45.       JSlider slider = new JSlider();  46.       addSlider(slider, "Plain");  47.  48.       // add a slider with major and minor ticks  49.  50.       slider = new JSlider();  51.       slider.setPaintTicks(true);  52.       slider.setMajorTickSpacing(20);  53.       slider.setMinorTickSpacing(5);  54.       addSlider(slider, "Ticks");  55.  56.       // add a slider that snaps to ticks  57.  58.       slider = new JSlider();  59.       slider.setPaintTicks(true);  60.       slider.setSnapToTicks(true);  61.       slider.setMajorTickSpacing(20);  62.       slider.setMinorTickSpacing(5);  63.       addSlider(slider, "Snap to ticks");  64.  65.       // add a filled slider  66.  67.       slider = new JSlider();  68.       slider.setPaintTicks(true);  69.       slider.setMajorTickSpacing(20);  70.       slider.setMinorTickSpacing(5);  71.       slider.putClientProperty("JSlider.isFilled",  72.          Boolean.TRUE);  73.       addSlider(slider, "Filled");  74.  75.       // add a filled and inverted slider  76.  77.       slider = new JSlider();  78.       slider.setPaintTicks(true);  79.       slider.setMajorTickSpacing(20);  80.       slider.setMinorTickSpacing(5);  81.       slider.putClientProperty("JSlider.isFilled",  82.          Boolean.TRUE);  83.       slider.setInverted(true);  84.       addSlider(slider, "Inverted");  85.  86.       // add a slider with numeric labels  87.  88.       slider = new JSlider();  89.       slider.setPaintTicks(true);  90.       slider.setPaintLabels(true);  91.       slider.setMajorTickSpacing(20);  92.       slider.setMinorTickSpacing(5);  93.       addSlider(slider, "Labels");  94.  95.       // add a slider with alphabetic labels  96.  97.       slider = new JSlider();  98.       slider.setPaintLabels(true);  99.       slider.setPaintTicks(true); 100.       slider.setMajorTickSpacing(20); 101.       slider.setMinorTickSpacing(5); 102. 103.       Hashtable labelTable = new Hashtable(); 104.       labelTable.put(new Integer(0), new JLabel("A")); 105.       labelTable.put(new Integer(20), new JLabel("B")); 106.       labelTable.put(new Integer(40), new JLabel("C")); 107.       labelTable.put(new Integer(60), new JLabel("D")); 108.       labelTable.put(new Integer(80), new JLabel("E")); 109.       labelTable.put(new Integer(100), new JLabel("F")); 110. 111.       slider.setLabelTable(labelTable); 112.       addSlider(slider, "Custom labels"); 113. 114.       // add a slider with icon labels 115. 116.       slider = new JSlider(); 117.       slider.setPaintTicks(true); 118.       slider.setPaintLabels(true); 119.       slider.setSnapToTicks(true); 120.       slider.setMajorTickSpacing(20); 121.       slider.setMinorTickSpacing(20); 122. 123.       labelTable = new Hashtable(); 124. 125.       // add card images 126. 127.       labelTable.put(new Integer(0), 128.          new JLabel(new ImageIcon("nine.gif"))); 129.       labelTable.put(new Integer(20), 130.          new JLabel(new ImageIcon("ten.gif"))); 131.       labelTable.put(new Integer(40), 132.          new JLabel(new ImageIcon("jack.gif"))); 133.       labelTable.put(new Integer(60), 134.          new JLabel(new ImageIcon("queen.gif"))); 135.       labelTable.put(new Integer(80), 136.          new JLabel(new ImageIcon("king.gif"))); 137.       labelTable.put(new Integer(100), 138.          new JLabel(new ImageIcon("ace.gif"))); 139. 140.       slider.setLabelTable(labelTable); 141.       addSlider(slider, "Icon labels"); 142. 143.       // add the text field that displays the slider value 144. 145.       textField = new JTextField(); 146.       Container contentPane = getContentPane(); 147.       contentPane.add(sliderPanel, BorderLayout.CENTER); 148.       contentPane.add(textField, BorderLayout.SOUTH); 149.    } 150. 151.    /** 152.       Adds a slider to the slider panel and hooks up the listener 153.       @param s the slider 154.       @param description the slider description 155.    */ 156.    public void addSlider(JSlider s, String description) 157.    { 158.       s.addChangeListener(listener); 159.       JPanel panel = new JPanel(); 160.       panel.add(s); 161.       panel.add(new JLabel(description)); 162.       sliderPanel.add(panel); 163.    } 164. 165.    public static final int DEFAULT_WIDTH = 350; 166.    public static final int DEFAULT_HEIGHT = 450; 167. 168.    private JPanel sliderPanel; 169.    private JTextField textField; 170.    private ChangeListener listener; 171. } 

javax.swing.JSlider 1.3

graphics/api_icon.gif
  • JSlider()

  • JSlider(int direction)

  • JSlider(int min, int max)

  • JSlider(int min, int max, int initialValue)

  • JSlider(int direction, int min, int max, int initialValue)

    construct a horizontal slider with the given direction, minimum, maximum, and initial values.

    Parameters:

    direction

    One of SwingConstants.HORIZONTAL or SwingConstants.VERTICAL. The default is horizontal.

     

    min, max

    The minimum and maximum for the slider values. Defaults are 0 and 100.

     

    initialValue

    The initial value for the slider. The default is 50.

  • void setPaintTicks(boolean b)

    If b is true, then ticks are displayed.

  • void setMajorTickSpacing(int units)

  • void setMinorTickSpacing(int units)

    set major or minor ticks at multiples of the given slider units.

  • void setPaintLabels(boolean b)

    If b is true, then tick labels are displayed.

  • slider.setLabelTable(Dictionary table)

    sets the components to use for the tick labels. Each key/value pair in the table has the form new Integer(value)/component.

  • void setSnapToTicks(boolean b)

    If b is true, then the slider snaps to the closest tick after each adjustment.

The JSpinner Component

A JSpinner is a text field with two small buttons on the side that let you increment and decrement the value stored in the field (see Figure 9-21).

Figure 9-21. Several variations of the JSpinner component

graphics/09fig21.gif

The values in the spinner can be numbers, dates, values from a list, or, in the most general case, any sequence of values for which predecessors and successors can be determined. The JSpinner class defines standard data models for the first three cases. You can define your own data model to describe arbitrary sequences.

By default, a spinner manages an integer, and the buttons increment or decrement it by one. You can get the current value by calling the setValue method. That method returns an Object. Cast it to an Integer and retrieve the wrapped value.

 JSpinner defaultSpinner = new JSpinner(); . . . int value = ((Integer)defaultSpinner.getValue()).intValue(); 

You can change the increment to a value other than 1, and also supply lower and upper bounds. Here is a spinner with starting value 5, bounded between 0 and 10, and an increment of 0.5:

 JSpinner boundedSpinner = new JSpinner(    new SpinnerNumberModel(5, 0, 10, 0.5)); 

There are two SpinnerNumberModel constructors, one with only int parameters, and one with double parameters. If any of the parameters are floating-point numbers, the second constructor is used. It sets the spinner value to a Double object.

Spinners aren't restricted to numeric values. You can have a spinner iterate through any collection of values. Simply pass a SpinnerListModel to the Spinner constructor. You can construct a SpinnerListModel from an array or a class implementing the List interface (such as an ArrayList). In our sample program, we display a spinner control with all available font names.

 String[] fonts = GraphicsEnvironment       .getLocalGraphicsEnvironment()       .getAvailableFontFamilyNames(); JSpinner listSpinner = new JSpinner(new SpinnerListModel(fonts)); 

However, we found that the direction of the iteration was mildly confusing, because it is opposite from the user experience with a combo box. In a combo box, higher values are below lower values, so you would expect the downward arrow to navigate towards higher values. But the spinner increments the array index so that the upward arrow yields higher values. There is no provision for reversing the traversal order in the SpinnerListModel, but an impromptu anonymous subclass yields the desired result:

 JSpinner reverseListSpinner = new JSpinner(    new SpinnerListModel(fonts)    {       public Object getNextValue()       {          return super.getPreviousValue();       }       public Object getPreviousValue()       {           return super.getNextValue();       }    }); 

Try out both versions and see which you find more intuitive.

Another good use for a spinner is for a date that the user can increment or decrement. You get such a spinner, initialized with today's date, with the call

 JSpinner dateSpinner = new JSpinner(new SpinnerDateModel()); 

However, if you look carefully at Figure 9-21, you will see that the spinner text shows both date and time, such as

 3/12/02 7:23 PM 

The time doesn't make any sense for a date picker. It turns out to be somewhat difficult to make the spinner show just the date. Here is the magic incantation:

 JSpinner betterDateSpinner = new JSpinner(    new SpinnerDateModel()); String pattern = ((SimpleDateFormat)    DateFormat.getDateInstance()).toPattern(); betterDateSpinner.setEditor(new JSpinner.DateEditor(    betterDateSpinner, pattern)); 

Using the same approach, you can also make a time picker. Then use the SpinnerDateModel constructor that lets you specify a Date, the lower and upper bounds (or null if there are no bounds), and the Calendar field (such as Calendar.HOUR) to be modified.

 JSpinner timeSpinner = new JSpinner(new SpinnerDateModel(       new GregorianCalendar(2000, Calendar.JANUARY, 1,          12, 0, 0).getTime(), null, null, Calendar.HOUR)); 

However, if you want to update the minutes in 15-minute increments, then you exceed the capabilities of the standard SpinnerDateModel class.

You can display arbitrary sequences in a spinner by defining your own spinner model. In our sample program, we have a spinner that iterates through all permutations of the string "meat." You can get to "mate," "meta," "team," and another 20 permutations by clicking the spinner buttons.

When you define your own model, you should extend the AbstractSpinnerModel class and define the following four methods:

 Object getValue() void setValue(Object value) Object getNextValue() Object getPreviousValue() 

The getValue method returns the value stored by the model. The setValue method sets a new value. It should throw an IllegalArgumentException if the new value is not appropriate.

graphics/caution_icon.gif

The setValue method must call the fireStateChanged method after setting the new value. Otherwise, the spinner field won't be updated.

The getNextValue and getPreviousValue methods return the values that should come after or before the current value, or null if the end of the traversal has been reached.

graphics/caution_icon.gif

The getNextValue and getPreviousValue methods should not change the current value. When a user clicks on the upward arrow of the spinner, the getNextValue method is called. If the return value is not null, it is set by calling setValue.

In the sample program, we use a standard algorithm to determine the next and previous permutations. The details of the algorithm are not important.

Example 9-11 shows how to generate the various spinner types. Click on the Ok button to see the spinner values.

Example 9-11 SpinnerTest.java
   1. import java.awt.*;   2. import java.awt.event.*;   3. import java.text.*;   4. import java.util.*;   5. import javax.swing.*;   6.   7. /**   8.    A program to test spinners.   9. */  10. public class SpinnerTest  11. {  12.    public static void main(String[] args)  13.    {  14.       SpinnerFrame frame = new SpinnerFrame();  15.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  16.       frame.show();  17.    }  18. }  19.  20. /**  21.    A frame with a panel that contains several spinners and  22.    a button that displays the spinner values.  23. */  24. class SpinnerFrame extends JFrame  25. {  26.    public SpinnerFrame()  27.    {  28.       setTitle("SpinnerTest");  29.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);  30.       Container contentPane = getContentPane();  31.       JPanel buttonPanel = new JPanel();  32.       okButton = new JButton("Ok");  33.       buttonPanel.add(okButton);  34.       contentPane.add(buttonPanel, BorderLayout.SOUTH);  35.  36.       mainPanel = new JPanel();  37.       mainPanel.setLayout(new GridLayout(0, 3));  38.       contentPane.add(mainPanel, BorderLayout.CENTER);  39.  40.       JSpinner defaultSpinner = new JSpinner();  41.       addRow("Default", defaultSpinner);  42.  43.       JSpinner boundedSpinner = new JSpinner(  44.          new SpinnerNumberModel(5, 0, 10, 0.5));  45.       addRow("Bounded", boundedSpinner);  46.  47.       String[] fonts = GraphicsEnvironment  48.          .getLocalGraphicsEnvironment()  49.          .getAvailableFontFamilyNames();  50.  51.       JSpinner listSpinner = new JSpinner(  52.          new SpinnerListModel(fonts));  53.       addRow("List", listSpinner);  54.  55.       JSpinner reverseListSpinner = new JSpinner(  56.          new  57.             SpinnerListModel(fonts)  58.             {  59.                public Object getNextValue()  60.                {  61.                   return super.getPreviousValue();  62.                }  63.                public Object getPreviousValue()  64.                {  65.                   return super.getNextValue();  66.                }  67.             });  68.       addRow("Reverse List", reverseListSpinner);  69.  70.       JSpinner dateSpinner = new JSpinner(  71.          new SpinnerDateModel());  72.       addRow("Date", dateSpinner);  73.  74.       JSpinner betterDateSpinner = new JSpinner(  75.          new SpinnerDateModel());  76.       String pattern = ((SimpleDateFormat)  77.          DateFormat.getDateInstance()).toPattern();  78.       betterDateSpinner.setEditor(new JSpinner.DateEditor(  79.          betterDateSpinner, pattern));  80.       addRow("Better Date", betterDateSpinner);  81.  82.       JSpinner timeSpinner = new JSpinner(  83.          new SpinnerDateModel(  84.             new GregorianCalendar(2000, Calendar.JANUARY, 1,  85.                12, 0, 0).getTime(), null, null, Calendar.HOUR));  86.       addRow("Time", timeSpinner);  87.  88.       JSpinner permSpinner = new JSpinner(  89.          new PermutationSpinnerModel("meat"));  90.       addRow("Word permutations", permSpinner);  91.    }  92.  93.    /**  94.       Adds a row to the main panel.  95.       @param labelText the label of the spinner  96.       @param spinner the sample spinner  97.    */  98.    public void addRow(String labelText, final JSpinner spinner)  99.    { 100.       mainPanel.add(new JLabel(labelText)); 101.       mainPanel.add(spinner); 102.       final JLabel valueLabel = new JLabel(); 103.       mainPanel.add(valueLabel); 104.       okButton.addActionListener(new 105.          ActionListener() 106.          { 107.             public void actionPerformed(ActionEvent event) 108.             { 109.                Object value = spinner.getValue(); 110.                valueLabel.setText(value.toString()); 111.             } 112.          }); 113.    } 114. 115.    public static final int DEFAULT_WIDTH = 400; 116.    public static final int DEFAULT_HEIGHT = 250; 117. 118.    private JPanel mainPanel; 119.    private JButton okButton; 120. } 121. 122. /** 123.    A model that dynamically generates word permutations 124. */ 125. class PermutationSpinnerModel extends AbstractSpinnerModel 126. { 127.    /** 128.       Constructs the model. 129.       @param w the word to permute 130.    */ 131.    public PermutationSpinnerModel(String w) 132.    { 133.       word = w; 134.    } 135. 136.    public Object getValue() 137.    { 138.       return word; 139.    } 140. 141.    public void setValue(Object value) 142.    { 143.       if (!(value instanceof String)) 144.          throw new IllegalArgumentException(); 145.       word = (String)value; 146.       fireStateChanged(); 147.    } 148. 149.    public Object getNextValue() 150.    { 151.       StringBuffer buffer = new StringBuffer(word); 152.       for (int i = buffer.length() - 1; i > 0; i--) 153.       { 154.          if (buffer.charAt(i - 1) < buffer.charAt(i)) 155.          { 156.             int j = buffer.length() - 1; 157.             while (buffer.charAt(i - 1) > buffer.charAt(j)) j--; 158.             swap(buffer, i - 1, j); 159.             reverse(buffer, i, buffer.length() - 1); 160.             return buffer.toString(); 161.          } 162.       } 163.       reverse(buffer, 0, buffer.length() - 1); 164.       return buffer.toString(); 165.    } 166. 167.    public Object getPreviousValue() 168.    { 169.       StringBuffer buffer = new StringBuffer(word); 170.       for (int i = buffer.length() - 1; i > 0; i--) 171.       { 172.          if (buffer.charAt(i - 1) > buffer.charAt(i)) 173.          { 174.             int j = buffer.length() - 1; 175.             while (buffer.charAt(i - 1) < buffer.charAt(j)) j--; 176.             swap(buffer, i - 1, j); 177.             reverse(buffer, i, buffer.length() - 1); 178.             return buffer.toString(); 179.          } 180.       } 181.       reverse(buffer, 0, buffer.length() - 1); 182.       return buffer.toString(); 183.    } 184. 185.    private static void swap(StringBuffer buffer, int i, int j) 186.    { 187.       char temp = buffer.charAt(i); 188.       buffer.setCharAt(i, buffer.charAt(j)); 189.       buffer.setCharAt(j, temp); 190.    } 191. 192.    private static void reverse(StringBuffer buffer, int i, int j) 193.    { 194.       while (i < j) { swap(buffer, i, j); i++; j--; } 195.    } 196. 197.    private String word; 198. } 

javax.swing.JSpinner 1.4

graphics/api_icon.gif
  • JSpinner()

    constructs a spinner that edits an integer with starting value 0, increment 1, and no bounds.

  • JSpinner(SpinnerModel model)

    constructs a spinner that uses the given data model.

  • Object getValue()

    gets the current value of the spinner.

  • void setValue(Object value)

    attempts to set the value of the spinner. Throws an IllegalArgumentException if the model does not accept the value.

  • void setEditor(JComponent editor)

    sets the component that is used for editing the spinner value.

javax.swing.SpinnerNumberModel 1.4

graphics/api_icon.gif
  • SpinnerNumberModel(int initval, int minimum, int maximum, int stepSize)

  • SpinnerNumberModel(double initval, double minimum, double maximum, double stepSize)

    These constructors yield number models that manage an Integer or Double value. Use the MIN_VALUE and MAX_VALUE constants of the Integer and Double classes for unbounded values.

    Parameters:

    initval

    the initial value

     

    minimum

    the minimum valid value

     

    maximum

    the maximum valid value

     

    stepSize

    the increment or decrement of each spin

javax.swing.SpinnerListModel 1.4

graphics/api_icon.gif
  • SpinnerListModel(Object[] values)

  • SpinnerListModel(List values)

    These constructors yield models that select a value from among the given values.

javax.swing.SpinnerDateModel 1.4

graphics/api_icon.gif
  • SpinnerDateModel()

    constructs a date model with today's date as the initial value, no lower or upper bounds, and an increment of Calendar.DAY_OF_MONTH.

  • SpinnerDateModel(Date initval, Comparable minimum, Comparable maximum, int step)

    Parameters:

    initval

    The initial value.

     

    minimum

    The minimum valid value, or null if no lower bound is desired.

     

    maximum

    The maximum valid value, or null if no lower bound is desired.

     

    step

    The date field to increment or decrement of each spin. One of the constants ERA, YEAR, MONTH, WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_MONTH, DAY_OF_YEAR, DAY_OF_WEEK, DAY_OF_WEEK_IN_MONTH, AM_PM, HOUR, HOUR_OF_DAY, MINUTE, SECOND, or MILLISECOND of the Calendar class.

javax.text.SimpleDateFormat 1.1

graphics/api_icon.gif
  • String toPattern() 1.2

    gets the editing pattern for this date formatter. A typical pattern is "yyyy-MM-dd". See the SDK documentation for more details about the pattern.

javax.swing.JSpinner.DateEditor 1.4

graphics/api_icon.gif
  • DateEditor(JSpinner spinner, String pattern)

    Parameters:

    spinner

    the spinner to whom this editor belongs

     

    pattern

    the format pattern for the associated SimpleDateFormat

javax.swing.AbstractSpinnerModel 1.4

graphics/api_icon.gif
  • Object getValue()

    gets the current value of the model.

  • void setValue(Object value)

    attempts to set a new value for the model. Throws an IllegalArgumentException if the value is not acceptable. When overriding this method, you should call fireStateChanged after setting the new value.

  • Object getNextValue()

  • Object getPreviousValue()

    These methods compute (but do not set) the next or previous value in the sequence that this model defines.


       
    Top
     



    Core Java 2(c) Volume I - Fundamentals
    Building on Your AIX Investment: Moving Forward with IBM eServer pSeries in an On Demand World (MaxFacts Guidebook series)
    ISBN: 193164408X
    EAN: 2147483647
    Year: 2003
    Pages: 110
    Authors: Jim Hoskins

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net