Java Reference
In-Depth Information
The
value
property allows you to change the current setting for the component. The
nextValue
and
previousValue
properties allow you to peek at entries of the
model
in the
different directions, without changing the selection within the application itself.
Listening for JSpinner Events with a ChangeListener
The
JSpinner
directly supports a single type of event listener:
ChangeListener
. Among other
places, the listener is notified when the
commitEdit()
method is called for the associated
component, telling you the spinner value changed. To demonstrate, Listing 14-1 attaches a
custom
ChangeListener
to the source used to generate the program associated with Figure 14-1.
Listing 14-1.
JSpinner with ChangeListener
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import java.util.*;
public class SpinnerSample {
public static void main (String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateFormatSymbols symbols =
new DateFormatSymbols(Locale.FRENCH);
ChangeListener listener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println("Source: " + e.getSource());
}
};
String days[] = symbols.getWeekdays();
SpinnerModel model1 = new SpinnerListModel(days);
JSpinner spinner1 = new JSpinner(model1);
spinner1.addChangeListener(listener);
JLabel label1 = new JLabel("French Days/List");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.NORTH);