How can I make a JSpinner object have its entire contents highlighted so that user input does not require deleting when focus is gained?

StackOverflow https://stackoverflow.com/questions/21225401

  •  30-09-2022
  •  | 
  •  

Question

Not much to add to the Title question.

Here's what tabbing to the first box looks like, with cursor before the first character in the field, so that the user will have to delete the character if he wishes to enter his own month, day, or year number:

enter image description here

Here's what I'd like, when the field is tabbed to (or otherwise selected), so the user doesn't have to delete the character(s) presented if he wishes to enter his own year, etc.:

enter image description here

I can accomplish this for a JTextField like so, for example:

txtDateFrom.select(0,99);

But .select() isn't a method for JSpinner.

(I realize that this raises the question, "Why use a spinner?" but the obvious answer is that I'd like both methods of selecting to be available, as is common in design.)

(A much less pressing but related matter... I made an integer array of 100 year-dates [e.g., 2014] named years and used SpinnerListModel(years) because when using the SpinnerNumberModel, a year would be displayed as 2,014. I can live with what I've done, but is there a less-brute-force way? There's no method containing "format" that I could find for this method.)

Was it helpful?

Solution

This works in Java 1.7.0_51, in Windows and Linux. I don't have the ability to test it in OS X.

JSpinner.DefaultEditor editor =
    (JSpinner.DefaultEditor) spinner.getEditor();

editor.getTextField().addFocusListener(new FocusAdapter() {
    @Override
    public void focusGained(FocusEvent event) {
        final JTextField textField = (JTextField) event.getComponent();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        textField.selectAll();
                    }
                });
            }
        });
    }
});

Side note: Have you considered replacing your three JSpinners with a single JSpinner like this?

JSpinner spinner = new JSpinner(new SpinnerDateModel());
spinner.setEditor(new JSpinner.DateEditor(spinner, "MM/dd/yyyy"));

The up/down arrow buttons (and arrow keys) will change whichever field contains the text cursor.

It won't solve your focus issue, but you may decide that the issue is less of an issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top