JTextField auto select works correctly. The spinner one does not behave
as expected. Because the code is small, I pasted it below.
package com.katalisindonesia.swingpack.support;
import javax.swing.JTextField;
import javax.swing.JSpinner;
import javax.swing.text.JTextComponent;
import java.awt.EventQueue;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
/*
* User: thomas
* Date: Jul 1, 2005
* Time: 2:07:30 PM
*/
/**
* Add auto select feature in component when focused.
*
* @author thomas
*/
public class AutoSelect {
private boolean enabled = true;
public void install(final JTextField textField) {
textField.addFocusListener(new TextComponentFocusListener(textField));
}
public void install (final JSpinner spinner) {
if (spinner.getEditor() instanceof JSpinner.DefaultEditor) {
spinner.addFocusListener(new TextComponentFocusListener(((JSpinner.DefaultEditor)spinner.getEditor()).getTextField()));
}
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
class TextComponentFocusListener
implements FocusListener {
private JTextComponent textComponent;
TextComponentFocusListener(JTextComponent textComponent) {
this.textComponent = textComponent;
}
public void focusGained(FocusEvent e) {
if (enabled) {
EventQueue.invokeLater(
new Runnable() {
public void run() {
textComponent.selectAll();
}
});
}
}
public void focusLost(FocusEvent e) {
if (enabled) {
EventQueue.invokeLater(
new Runnable() {
public void run() {
textComponent.select(0, 0);
}
});
}
}
}
}
Use is simple. First, instantiate the auto select.
AutoSelect autoSelect = new AutoSelect();
Then, install to any component you want.
autoSelect.install(textField0);
autoSelect.install(textField1);
...
You may enable or disable it by using setEnabled().
I do this instead of subclassing the JTextField because I think that it
would scale better than the latter.
Please comment on it. Thanks!
No comments:
Post a Comment