views:

41

answers:

1

In the code sample below, if a user changes the contents of the JFormattedTextField then presses Enter, the dialog is supposed to act as if the OK button is pressed. But it takes two presses of Enter for this to happen.

The plain vanilla JTextField always acts as I would expect - changing the text then pressing Enter activates the OK button straight away.

This in on Mac OS X 10.6 with the current Mac Java update 1.6.0_20.

Is this a work-around? Is this a Mac specific problem?

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.text.NumberFormat;
import java.text.ParseException;

public class ScratchSpace {


    public static void main(final String[] args) throws ParseException {
        final JDialog dialog = new JDialog((Frame) null, "Test", true);
        dialog.setLayout(new FlowLayout());

        dialog.add(new JLabel("text field: "));
        dialog.add(new JTextField(20));

        dialog.add(new JLabel("formatted text field: "));
        final JFormattedTextField formattedTextField = new JFormattedTextField(NumberFormat.getIntegerInstance());
        formattedTextField.setValue(42);
        formattedTextField.setColumns(20);
        dialog.add(formattedTextField);

        final JButton okButton = new JButton(new AbstractAction("OK") {
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });

        dialog.add(okButton);
        dialog.getRootPane().setDefaultButton(okButton);
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }

}
+1  A: 

Adding this code solved the problem,

formattedTextField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        dialog.dispose();
    }
});
Bragboy