Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - Make JSpinner Select Text When Focused

I would like to change the behavior of a JSpinner so that when you click on the text, it selects it. This makes it easier to replace the field with the value that you want. Unfortunately, I can't get the behavior to work and instead, it just inserts the cursor in the text without selecting what is already there.

I have tried adding a focus Listener to both the JSpinner itself and the text area itself, via ((DefaultEditor) this.getEditor()).getTextField(), yet neither of these seem to have the intended effect. My code (for the JSpinner itself) is as follows:

spinner.addFocusListener(new FocusAdapter(){
            @Override
            public void focusGained(FocusEvent e) {
                ((DefaultEditor) ((JSpinner) e.getSource()).getEditor()).getTextField().selectAll();
            }
        }); 

I'm not sure what the problem is. If it matters, I'm running Mac OS 10.7.5 and Java 6u43.

EDIT: I put a System.out.println right at the beginning of the focusGained method and discovered that it was never called. So it looks like getting focus on the JSpinner isn't registering. Again, I tried putting the focusAdpater both on the spinner and on the text field (not at the same time though).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't know about a Mac but I've used this code on Windows:

JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor)spinner.getEditor();
JTextField textField = editor.getTextField();
textField.addFocusListener( new FocusAdapter()
{
    public void focusGained(final FocusEvent e)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                JTextField tf = (JTextField)e.getSource();
                tf.selectAll();
            }
        });

    }

});

I've also used this code for selecting text on a JFormattedTextField.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...