Skip to content
Advertisement

Selecting a part of text in JSpinner on click

I have a JSpinner with SpinnerDateModel. I want when users click on any part of the editor (the date, month, or year), it will automatically select them. So I wrote this:

JSpinner dateSpn = new JSpinner();
dateSpn.setModel(new SpinnerDateModel());
JSpinner.DateEditor editor = new JSpinner.DateEditor(dateSpn, "dd-MM-yyyy");
dateSpn.setEditor(editor);
JFormattedTextField field = editor.getTextField();
field.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent evt) {
        int i = field.getCaretPosition();
        if (i <= 2) {
            field.select(0, 2);
        } else if (i >= 3 && i <= 5) {
            field.select(3, 5);
        } else if (i >= 6){
            field.select(6, 10);
        }
    }
});

But when the first time it clicked, nothing happened. Although when I click it again, it works perfectly. Where’s wrong with my code?

Advertisement

Answer

From the documentation of MouseAdapter#mousePressed():

Invoked when a mouse button has been pressed on a component.

Which means this is executed when the mouse has only been pressed (not yet released mind you). So this is the first of the clicked / pressed / released methods to be invoked.

The issue you are having then is, that at this point in time, when mousePressed is invoked, your JFormattedTextFields caret position might not have been correctly updated yet. Hence the issue you are encountering.

The solution is to switch to mouseClicked() (or mouseReleased() as an alternative), because at that point, you can be sure that your JFormattedTextField has been updated correctly and the invoked method gets the correct value.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement