JFormattedTextField - NumberFormat interferes with selectAll()
Hi,
I have a JPanel with two JFormattedTextFields.
I wish to configure them with NumberFormat and
InputVerifiers. I also wish to set my own
FocusTraversalKeys on the JPanel and to use the
JFormattedTextField.selectAll() method upon the
FOCUS_GAINED event.
The problem I'm having with the following code is:
When I construct the JFormattedTextFields with a
NumberFormat, the selectAll() method seems to have
no effect.
When I construct the JFormattedTextFields without a
NumberFormat, the selectAll() method seems to work
as I had expected; the JFormattedTextField gaining
focus has it's text selected.
Can someone tell what I'm doing wrong, or what else
I need to do to get my desired behavior?
Thanks,
Jeff Higgins
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Test extends JPanel
implements FocusListener {
private JLabel test1Label;
private JLabel test2Label;
private JFormattedTextField test1Field;
private JFormattedTextField test2Field;
public Test() {
super(new BorderLayout());
test1Label = new JLabel("Test One");
test2Label = new JLabel("Test Two");
test1Field = new JFormattedTextField(NumberFormat.getIntegerInstance());
test1Field.setColumns(10);
test1Field.addFocusListener(this);
test2Field = new JFormattedTextField(NumberFormat.getNumberInstance());
test2Field.setColumns(10);
test2Field.addFocusListener(this);
test1Label.setLabelFor(test1Field);
test2Label.setLabelFor(test2Field);
JPanel labelPane = new JPanel(new GridLayout(0,1));
labelPane.add(test1Label);
labelPane.add(test2Label);
JPanel fieldPane = new JPanel(new GridLayout(0,1));
fieldPane.add(test1Field);
fieldPane.add(test2Field);
Set<AWTKeyStroke> newForwardKeys = new HashSet<AWTKeyStroke>(1);
newForwardKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,0));
newForwardKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER,0));
fieldPane.setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.unmodifiableSet(newForwardKeys));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
add(labelPane, BorderLayout.CENTER);
add(fieldPane, BorderLayout.LINE_END);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test Focus");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Test();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public void focusGained(FocusEvent e) {
((JFormattedTextField)e.getComponent()).selectAll();
}
public void focusLost(FocusEvent e) {}
}