Example usage for javax.swing.text NumberFormatter setFormat

List of usage examples for javax.swing.text NumberFormatter setFormat

Introduction

In this page you can find the example usage for javax.swing.text NumberFormatter setFormat.

Prototype

public void setFormat(Format format) 

Source Link

Document

Sets the format that dictates the legal values that can be edited and displayed.

Usage

From source file:components.IntegerEditor.java

public IntegerEditor(int min, int max) {
    super(new JFormattedTextField());
    ftf = (JFormattedTextField) getComponent();
    minimum = new Integer(min);
    maximum = new Integer(max);

    //Set up the editor for the integer cells.
    integerFormat = NumberFormat.getIntegerInstance();
    NumberFormatter intFormatter = new NumberFormatter(integerFormat);
    intFormatter.setFormat(integerFormat);
    intFormatter.setMinimum(minimum);//from w  w w.  j  ava 2s .  co m
    intFormatter.setMaximum(maximum);

    ftf.setFormatterFactory(new DefaultFormatterFactory(intFormatter));
    ftf.setValue(minimum);
    ftf.setHorizontalAlignment(JTextField.TRAILING);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);

    //React when the user presses Enter while the editor is
    //active.  (Tab is handled as specified by
    //JFormattedTextField's focusLostBehavior property.)
    ftf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "check");
    ftf.getActionMap().put("check", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if (!ftf.isEditValid()) { //The text is invalid.
                if (userSaysRevert()) { //reverted
                    ftf.postActionEvent(); //inform the editor
                }
            } else
                try { //The text is valid,
                    ftf.commitEdit(); //so use it.
                    ftf.postActionEvent(); //stop editing
                } catch (java.text.ParseException exc) {
                }
        }
    });
}