也许您可以使用 FocusListener。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class SpinnerFocusTest {
private static final String PATTERN = "m:ss";
public JComponent makeUI() {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(60*1000);
Date value = c.getTime();
SpinnerDateModel m = new SpinnerDateModel(
value, null, null, Calendar.MINUTE);
JSpinner sp1 = new JSpinner(m);
sp1.setEditor(new JSpinner.DateEditor(sp1, PATTERN));
JSpinner sp2 = new JSpinner(m);
final JSpinner.DateEditor editor =
new JSpinner.DateEditor(sp2, PATTERN);
sp2.setEditor(editor);
editor.getTextField().addFocusListener(new FocusAdapter() {
@Override public void focusGained(FocusEvent e) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
JTextField f = editor.getTextField();
int i = f.getText().lastIndexOf(":");
f.select(i+1, i+3);
}
});
}
});
JPanel p = new JPanel(new GridLayout(2,1,5,5));
p.add(sp1);
p.add(sp2);
JPanel panel = new JPanel(new BorderLayout());
panel.add(p, BorderLayout.NORTH);
panel.setBorder(BorderFactory.createEmptyBorder(8,8,8,8));
return panel;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame("");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new SpinnerFocusTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}