Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...