Subpages: 1. JBounded-range components overview
2. Basic JScrollBar example
3. JSlider date chooser
4. JSliders in a JPEG image editor
5. JProgressBar in an FTP client application
13.3 JSlider date chooser
In this example we'll show how three JSliders can be combined to allow date selection. We will also address some resizing issues and show how to dynamically change JSlider's annotation components and tick spacing based on size constraints.
Note: While month and day are limited values, year is not. We can use a JSlider to select year only if we define a limited range of years to choose from. In this example we bound the year slider value between 1990 and 2010.

Figure 13.3 JSliders with dynamically changable bound values, tick spacing, and annotation components.
<<file figure13-3.gif>>
UI Guideline :
Feedback in Readable form
Using Sliders to pick the values for a date may be an interesting method for data input, however, it does not lend itself to reading and clear output communication. This is fixed by the use of the clearly human readable form at the top of the dialog. This directly follows the advice that Sliders should be used with immediate visual feedback.
Visual Noise
Visual noise or clutter is avoided through the spacing of annotations and the avoiding the temptation to annotate each day and each year. The change in rendering as the device is resized to smaller is also a clear example of how extra coding and the adoption of an advanced technique can aid visual communication and usability.

Figure 13.4 JSliders showing altered maximum bound and annotation labels.
<<file figure13-4.gif>>
The Code: DateSlider.java
see \Chapter13\3
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class DateSlider extends JFrame
{
public final static Dimension RIGID_DIMENSION =
new Dimension(1,3);
protected JLabel m_lbDate;
protected JSlider m_slYear;
protected JSlider m_slMonth;
protected JSlider m_slDay;
protected Hashtable m_labels;
protected GregorianCalendar m_calendar;
protected SimpleDateFormat m_dateFormat;
public DateSlider() {
super("Date Slider");
setSize(500, 340);
m_calendar = new GregorianCalendar();
Date currDate = new Date();
m_calendar.setTime(currDate);
m_dateFormat = new SimpleDateFormat("EEE, MMM d, yyyyy");
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 1));
JPanel p = new JPanel();
p.setBorder(new TitledBorder(new EtchedBorder(),
"Selected Date"));
m_lbDate = new JLabel(
m_dateFormat.format(currDate) + " ");
m_lbDate.setFont(new Font("Arial",Font.BOLD,24));
p.add(m_lbDate);
p1.add(p);
m_slYear = new JSlider(JSlider.HORIZONTAL, 1990, 2010,
m_calendar.get(Calendar.YEAR));
m_slYear.setPaintLabels(true);
m_slYear.setMajorTickSpacing(5);
m_slYear.setMinorTickSpacing(1);
m_slYear.setPaintTicks(true);
DateListener lst = new DateListener();
m_slYear.addChangeListener(lst);
p = new JPanel();
p.setBorder(new TitledBorder(new EtchedBorder(), "Year"));
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(Box.createRigidArea(RIGID_DIMENSION));
p.add(m_slYear);
p.add(Box.createRigidArea(RIGID_DIMENSION));
p1.add(p);
m_slMonth = new JSlider(JSlider.HORIZONTAL, 1, 12,
m_calendar.get(Calendar.MONTH)+1);
String[] months =
(new DateFormatSymbols()).getShortMonths();
m_labels = new Hashtable(12);
for (int k=0; k<12; k++)
m_labels.put(new Integer(k+1), new JLabel(
months[k], JLabel.CENTER ));
m_slMonth.setLabelTable(m_labels);
m_slMonth.setPaintLabels(true);
m_slMonth.setMajorTickSpacing(1);
m_slMonth.setPaintTicks(true);
m_slMonth.addChangeListener(lst);
p = new JPanel();
p.setBorder(new TitledBorder(new EtchedBorder(), "Month"));
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(Box.createRigidArea(RIGID_DIMENSION));
p.add(m_slMonth);
p.add(Box.createRigidArea(RIGID_DIMENSION));
p1.add(p);
int maxDays = m_calendar.getActualMaximum(
Calendar.DAY_OF_MONTH);
m_slDay = new JSlider(JSlider.HORIZONTAL, 1, maxDays,
m_calendar.get(Calendar.DAY_OF_MONTH));
m_slDay.setPaintLabels(true);
m_slDay.setMajorTickSpacing(5);
m_slDay.setMinorTickSpacing(1);
m_slDay.setPaintTicks(true);
m_slDay.addChangeListener(lst);
p = new JPanel();
p.setBorder(new TitledBorder(new EtchedBorder(), "Day"));
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(Box.createRigidArea(RIGID_DIMENSION));
p.add(m_slDay);
p.add(Box.createRigidArea(RIGID_DIMENSION));
p1.add(p);
getContentPane().add(p1, BorderLayout.CENTER);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
enableEvents(ComponentEvent.COMPONENT_RESIZED);
setVisible(true);
}
protected void processComponentEvent(ComponentEvent e) {
if (e.getID() == ComponentEvent.COMPONENT_RESIZED) {
int w = getSize().width;
m_slYear.setLabelTable(null);
if (w > 200)
m_slYear.setMajorTickSpacing(5);
else
m_slYear.setMajorTickSpacing(10);
m_slYear.setPaintLabels(w > 100);
m_slMonth.setLabelTable(w > 300 ? m_labels : null);
if (w <= 300 && w >=200)
m_slMonth.setMajorTickSpacing(1);
else
m_slMonth.setMajorTickSpacing(2);
m_slMonth.setPaintLabels(w > 100);
m_slDay.setLabelTable(null);
if (w > 200)
m_slDay.setMajorTickSpacing(5);
else
m_slDay.setMajorTickSpacing(10);
m_slDay.setPaintLabels(w > 100);
}
}
public void showDate() {
m_calendar.set(m_slYear.getValue(),
m_slMonth.getValue()-1, 1);
int maxDays = m_calendar.getActualMaximum(
Calendar.DAY_OF_MONTH);
if (m_slDay.getMaximum() != maxDays) {
m_slDay.setValue(
Math.min(m_slDay.getValue(), maxDays));
m_slDay.setMaximum(maxDays);
m_slDay.repaint();
}
m_calendar.set(
m_slYear.getValue(), m_slMonth.getValue()-1,
m_slDay.getValue());
Date date = m_calendar.getTime();
m_lbDate.setText(m_dateFormat.format(date));
}
class DateListener implements ChangeListener
{
public void stateChanged(ChangeEvent e) {
showDate();
}
}
public static void main(String argv[]) {
new DateSlider();
}
}
Understanding the Code
Class DateSlider
DateSlider extends JFrame and declares seven instance variables and one class constant. Class constant:
Dimension RIGID_DIMENSION: used to create rigid areas above and below each slider.
Instance variables:
JLabel m_lbDate: label to display the selected date.
JSlider m_slYear: slider to select year.
JSlider m_slMonth: slider to select month.
JSlider m_slDay: slider to select day.
Hashtable m_labels: collection of labels to denote months by short names rather than numbers.
GregorianCalendar m_calendar: calendar to perform date manipulations.
SimpleDateFormat m_dateFormat: object to format the date as a string.
The DateSlider constructor initializes the m_calendar instance defined above, and date format m_dateFormat. A JPanel with a GridLayout of one column and four rows is used as a base panel, p1. JLabel m_lbDate using a large font is created, embedded in a JPanel with a simple TitledBorder, and placed in the first row.
The m_slYear slider is created and placed in the second row. This is used to select the year from the interval 1990 to 2010. Note that it takes its initial value from the current date. A number of settings are applied to m_slYear. The paintLabels and paintTicks properties are set to true to allow drawing ticks and labels, majorTickSpacing is set to 5 to draw majors ticks for every fifth value, and minorTickSpacing is set to 1 to draw minor ticks for every value. Finally a new DateListener instance (see below) is added as a ChangeListener to monitor changes to this slider's properties. Note that m_slYear is placed in a JPanel surrounded by a TitledBorder. Two rigid areas are added to ensure vertical spacing between our slider and this parent panel (see chapter 4 for more about Box and its invisible Filler components).
The m_slMonth slider is created and placed in the third row. This slider is used to select the month from the interval 1 to 12. This component is constructed similar to m_slYear, but receives a Hashtable of JLabels to denote months by short names rather than numbers. These names are taken from an instance of the DateFormatSymbols class (see API docs) and used to create pairs in a local m_labels Hashtable in the form: Integer representing slider value (from 1 to 12) as key, and JLabel with the proper text as value. Finally, the setLabelTable() method is invoked to assign these custom labels to the slider.
The m_slDay slider is created and placed in the fourth row. It is used to select the day of the month from an interval which dynamically changes depending on the current month and, for February, the year. Aside from this difference, m_slDay is constructed very similar to m_slYear.
Because a slider's tick annotation components may overlap each other and become unreadable if not enough space provided, it is up to us to account for this possibility. This becomes a more significant problem when (as in this example) slider components can resized by simply resizing the parent frame. To work around this problem we can simply enforce a certain frame size, however, this may not be desirable in all situations. If we are ever in such a situation we need to change our slider's properties dynamically depending on its size. For this reason the processComponentEvent() method is overridden to process resizing events that occur on the parent frame. Processing of these events is enabled in the DateSlider constructor with the enableEvents() method.
The processComponentEvent() method only responds to ComponentEvents with ID COMPONENT_RESIZED. For each of our three sliders this method changes the majorTickSpacing property based on the container's width. m_slDay and m_slYear receive a spacing of 5 if the width if greater than 200, and 10 otherwise. m_slMonth receives a majorTickSpacing of 1 if the conatiner's width is anywhere from 200 to 300, and 2 otherwise. If this width is greater than 300 our custom set of labels is used to annotate m_slMonth's major ticks. The default numerical labels are used otherwise. For each slider, if the width is less than 100 the paintLabels property is set to false, which disables all annotations. Otherwise paintLabels is set to true.
Our custom showDate() method is used to retrieve values from our sliders and display them in m_lbDate as the new selected date. First we determine the maximum number of days for the selected month by passing m_calendar a year, a month, and 1 as the day. Then, if necessary, we reset m_slDay's current and maximum values. Finally, we pass m_calendar a year, month, and the selected (possibly adjusted) day, retrieve a Date instance corresponding to these values, and invoke format() to retrieve a textual representation of the date.
Note: Java 2 does not really provide a direct way to convert a year, month, and day triplet into a Date instance (this functionality has been deprecated). We need to use Calendar.set() and Calendar.getTime() for this. Be aware that the day parameter is not checked against the maximum value for the selected month. Setting the day to 30 when the month is set to February will be silently treated as March, 2.
Class DateSlider.DateListener
The DateListener inner class implements the ChangeListener interface and is used to listen for changes in each of our sliders' properties. Its stateChanged() method simply calls the showDate() method described above.
Running the Code
Note how the date is selected and displayed, and the range of the "Day" slider is adjusted when a new month is selected. Figure 13.3 shows selection of February 29th 2000, demonstrating that this is a leap year.
Note: A leap year is a year evenly divisible by four, but not evenly divisible by 100. The first rule takes precedence, so years evenly divisible by 400 are leap years (2000 is a leap year, while 1900 is not).
Now try resizing the application frame to see how the slider annotations and ticks change to their more compact variants as the available space shrinks. Figure 13.4 illustrates.
UI Guideline :
Exact value selection
Although Sliders are best used for selection when an exact value is not needed, this example gets around it by providing an adequate gap between ticks, making an exact choice easy to achieve.
The use of a Slider for Year is an unusual choice, as Year is not normally a bounded input. However, in certain domains it may be a more suitable choice. You may for example know the limits of available years e.g. years on which an Olympic games was held. The tick value would be 4 and the bound would be from the first games in 1896 to the next in 2000. Once Year and Month have been displayed using Sliders it is visually attractive and consistent to use a Slider for Day. There may be some debate about doing so as the bound will change depending on the month selected. However, it is fair to argue that the changing bound on Day, as Month is selected gives a clear, instant, visual feedback of how many days are in the month, which meets with the criteria of providing instant feedback when using a Slider.



RSS feed Java FAQ News