Question

Am using a spinner for selecting time and facing the below issue,

StarttimeSpinner = new JSpinner();
Date time = new SimpleDateFormat("HHmmss", Locale.ENGLISH).parse("000000");
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateString = formatter.format(time);
StarttimeSpinner.setModel(new SpinnerListModel(new String[]{dateString}));

This spinner is in a JPanel. When i open the panel i cant able to change values in spinner its getting automatically reassign to dateString value(00:00:00). I can understand it is because of setModel but is there anyway i can Edit the value ?

Was it helpful?

Solution

When i open the panel i cant able to change values in spinner its getting automatically reassign to dateString value(00:00:00).

The thing is you're trying to change a value in a single element list:

StarttimeSpinner.setModel(new SpinnerListModel(new String[]{dateString}));

JSpinner is intended to allow users pick a selection in a list of possible values defined by its SpinnerModel. You can edit the spinner value if the new value is valid according to the model. So in this case you cannot edit the single element valid for the spinner model.

If your goal is make the spinner a time selector then consider use SpinnerDateModel as model and set an appropriate editor to the spinner (see JSpinner.DateEditor class):

SpinnerDateModel model = new SpinnerDateModel();
JSpinner spinner = new JSpinner(model);
spinner.setEditor(new JSpinner.DateEditor(spinner, "HH:mm:ss"));

See more in this answer by @MoritzPetersen and How to Use Spinners tutorial.

OTHER TIPS

try this example:

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;

public class Main {
    public static void main(String args[]) {
        JFrame frame = new JFrame("Demo Frame/SuRu");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout());
        frame.setBounds(200, 200, 500, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SpinnerDateModel dateModel = new SpinnerDateModel();
        JSpinner jSpinner = new JSpinner(dateModel);
        jSpinner.setEditor(new JSpinner.DateEditor(jSpinner, "hh:mm:ss dd/MM/yyyy"));
        contentPane.add(new JLabel("Change Date: "));
        contentPane.add(jSpinner);
        frame.setVisible(true);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top