Animesh Kumar Paul
Animesh Kumar Paul

Reputation: 2304

How to change the default selection on JSpinner?

I face a problem with JSpinner. I use the format of time in a spinner that is "hh:mm:ss,msmsms". When I go to increase the time with mouse without any selection on the spinner format means I am not select any part of the time such as hours, minutes, seconds, or millisecond - it always increase the hours as a default selection on hours.

I want to give this default selection on the second means when I am going to increase or decrease the time using the mouse, it works on the second(s) part.

E.G.

01:05:08,102

After clicking the spinner up state, then the below time come.

01:05:09,102

This is the code:

Start_time_jSpinner = new javax.swing.JSpinner();
Start_time_jSpinner.setModel(new SpinnerDateModel());
Start_time_jSpinner.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
Start_time_jSpinner.setEditor(new JSpinner.DateEditor(Start_time_jSpinner,   "HH:mm:ss,SSS"));

Upvotes: 3

Views: 1616

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168845

Even though the 'hour' field is selected, the value will increase/decrease by a second at a time on up/down arrow.

import java.util.Date;
import javax.swing.*;

public class SecondIncrement {

    SecondIncrement() {
        JSpinner spinner = new JSpinner();
        SpinnerDateModel dateModel = new SpinnerDateModel(){
            @Override 
            public Object getNextValue() {
                Date date = this.getDate();
                long millis = date.getTime();
                return new Date(millis+1000);
            }

            @Override 
            public Object getPreviousValue() {
                Date date = this.getDate();
                long millis = date.getTime();
                return new Date(millis-1000);
            }
        };
        spinner.setModel(dateModel);
        spinner.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        spinner.setEditor(new JSpinner.DateEditor(spinner, "HH:mm:ss,SSS"));
        JOptionPane.showMessageDialog(null, spinner);
    }

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SecondIncrement();
            }
        });
    }
}

Upvotes: 4

Related Questions