Example usage for javax.swing.text NumberFormatter NumberFormatter

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

Introduction

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

Prototype

public NumberFormatter(NumberFormat format) 

Source Link

Document

Creates a NumberFormatter with the specified Format instance.

Usage

From source file:Main.java

public static void main(String[] argv) {
    JFormattedTextField f = new JFormattedTextField(new BigDecimal("123.4567"));
    DefaultFormatter fmt = new NumberFormatter(new DecimalFormat("#.0###############"));
    fmt.setValueClass(f.getValue().getClass());
    DefaultFormatterFactory fmtFactory = new DefaultFormatterFactory(fmt, fmt, fmt);
    f.setFormatterFactory(fmtFactory);// w w  w  .java2  s .  c o m

    BigDecimal bigValue = (BigDecimal) f.getValue();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(2);//from w ww  . jav  a 2s. c  om
    format.setMinimumFractionDigits(2);
    format.setParseIntegerOnly(true);
    format.setRoundingMode(RoundingMode.HALF_UP);

    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setMaximum(1000);
    formatter.setMinimum(0.0);
    formatter.setAllowsInvalid(false);
    // formatter.setOverwriteMode(false);

    JFormattedTextField tf = new JFormattedTextField(formatter);
    tf.setColumns(10);
    tf.setValue(123456789.99);
    JFormattedTextField tf1 = new JFormattedTextField(formatter);
    tf1.setValue(1234567890.99);
    JFormattedTextField tf2 = new JFormattedTextField(formatter);
    tf2.setValue(1111.1111);
    JFormattedTextField tf3 = new JFormattedTextField(formatter);
    tf3.setValue(-1111.1111);
    JFormattedTextField tf4 = new JFormattedTextField(formatter);
    tf4.setValue(-56);

    JFrame frame = new JFrame("Test");
    frame.setLayout(new GridLayout(5, 0));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(tf);
    frame.add(tf1);
    frame.add(tf2);
    frame.add(tf3);
    frame.add(tf4);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

/**
 * Custom creation method for {@link JFormattedTextField}.
 *//*from  w w  w  .  ja  v  a2s.  c  om*/
public static JFormattedTextField createIntegerTextField(final int min, final int max, final int now,
        final int columnNumber) {
    final NumberFormatter formatter = new NumberFormatter(NumberFormat.getIntegerInstance());
    formatter.setMinimum(min);
    formatter.setMaximum(max);
    final JFormattedTextField TF = new JFormattedTextField(formatter);
    TF.setValue(now);
    TF.setColumns(columnNumber);
    return TF;
}

From source file:Main.java

public Main() {
    super(new BorderLayout());
    amountDisplayFormat = NumberFormat.getCurrencyInstance();
    System.out.println(amountDisplayFormat.format(1200));
    amountDisplayFormat.setMinimumFractionDigits(0);
    amountEditFormat = NumberFormat.getNumberInstance();
    amountField = new JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(amountDisplayFormat),
            new NumberFormatter(amountDisplayFormat), new NumberFormatter(amountEditFormat)));
    amountField.setValue(new Double(amount));
    amountField.setColumns(10);//from www.  j  ava  2s . c o  m
    amountField.addPropertyChangeListener("value", this);

    JPanel fieldPane = new JPanel(new GridLayout(0, 1));
    fieldPane.add(amountField);

    add(fieldPane, BorderLayout.LINE_END);
    add(new JButton("Hello"), BorderLayout.SOUTH);
}

From source file:FormatterFactoryDemo.java

public FormatterFactoryDemo() {
    super(new BorderLayout());
    setUpFormats();//w  ww  .jav  a  2  s  . c  om
    double payment = computePayment(amount, rate, numPeriods);

    // Create the labels.
    amountLabel = new JLabel(amountString);
    rateLabel = new JLabel(rateString);
    numPeriodsLabel = new JLabel(numPeriodsString);
    paymentLabel = new JLabel(paymentString);

    // Create the text fields and set them up.
    amountField = new JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(amountDisplayFormat),
            new NumberFormatter(amountDisplayFormat), new NumberFormatter(amountEditFormat)));
    amountField.setValue(new Double(amount));
    amountField.setColumns(10);
    amountField.addPropertyChangeListener("value", this);

    NumberFormatter percentEditFormatter = new NumberFormatter(percentEditFormat) {
        public String valueToString(Object o) throws ParseException {
            Number number = (Number) o;
            if (number != null) {
                double d = number.doubleValue() * 100.0;
                number = new Double(d);
            }
            return super.valueToString(number);
        }

        public Object stringToValue(String s) throws ParseException {
            Number number = (Number) super.stringToValue(s);
            if (number != null) {
                double d = number.doubleValue() / 100.0;
                number = new Double(d);
            }
            return number;
        }
    };
    rateField = new JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(percentDisplayFormat),
            new NumberFormatter(percentDisplayFormat), percentEditFormatter));
    rateField.setValue(new Double(rate));
    rateField.setColumns(10);
    rateField.addPropertyChangeListener("value", this);

    numPeriodsField = new JFormattedTextField();
    numPeriodsField.setValue(new Integer(numPeriods));
    numPeriodsField.setColumns(10);
    numPeriodsField.addPropertyChangeListener("value", this);

    paymentField = new JFormattedTextField(paymentFormat);
    paymentField.setValue(new Double(payment));
    paymentField.setColumns(10);
    paymentField.setEditable(false);
    paymentField.setForeground(Color.red);

    // Tell accessibility tools about label/textfield pairs.
    amountLabel.setLabelFor(amountField);
    rateLabel.setLabelFor(rateField);
    numPeriodsLabel.setLabelFor(numPeriodsField);
    paymentLabel.setLabelFor(paymentField);

    // Lay out the labels in a panel.
    JPanel labelPane = new JPanel(new GridLayout(0, 1));
    labelPane.add(amountLabel);
    labelPane.add(rateLabel);
    labelPane.add(numPeriodsLabel);
    labelPane.add(paymentLabel);

    // Layout the text fields in a panel.
    JPanel fieldPane = new JPanel(new GridLayout(0, 1));
    fieldPane.add(amountField);
    fieldPane.add(rateField);
    fieldPane.add(numPeriodsField);
    fieldPane.add(paymentField);

    // Put the panels in this panel, labels on left,
    // text fields on right.
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    add(labelPane, BorderLayout.CENTER);
    add(fieldPane, BorderLayout.LINE_END);
}

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 ww  .  jav a 2  s. c o 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) {
                }
        }
    });
}

From source file:components.ConversionPanel.java

ConversionPanel(Converter myController, String myTitle, Unit[] myUnits, ConverterRangeModel myModel) {
    if (MULTICOLORED) {
        setOpaque(true);//from ww  w .  j a  v a  2 s.c om
        setBackground(new Color(0, 255, 255));
    }
    setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(myTitle),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    //Save arguments in instance variables.
    controller = myController;
    units = myUnits;
    title = myTitle;
    sliderModel = myModel;

    //Create the text field format, and then the text field.
    numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    NumberFormatter formatter = new NumberFormatter(numberFormat);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);//seems to be a no-op --
    //aha -- it changes the value property but doesn't cause the result to
    //be parsed (that happens on focus loss/return, I think).
    //
    textField = new JFormattedTextField(formatter);
    textField.setColumns(10);
    textField.setValue(new Double(sliderModel.getDoubleValue()));
    textField.addPropertyChangeListener(this);

    //Add the combo box.
    unitChooser = new JComboBox();
    for (int i = 0; i < units.length; i++) { //Populate it.
        unitChooser.addItem(units[i].description);
    }
    unitChooser.setSelectedIndex(0);
    sliderModel.setMultiplier(units[0].multiplier);
    unitChooser.addActionListener(this);

    //Add the slider.
    slider = new JSlider(sliderModel);
    sliderModel.addChangeListener(this);

    //Make the text field/slider group a fixed size
    //to make stacked ConversionPanels nicely aligned.
    JPanel unitGroup = new JPanel() {
        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(150, super.getPreferredSize().height);
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    };
    unitGroup.setLayout(new BoxLayout(unitGroup, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        unitGroup.setOpaque(true);
        unitGroup.setBackground(new Color(0, 0, 255));
    }
    unitGroup.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
    unitGroup.add(textField);
    unitGroup.add(slider);

    //Create a subpanel so the combo box isn't too tall
    //and is sufficiently wide.
    JPanel chooserPanel = new JPanel();
    chooserPanel.setLayout(new BoxLayout(chooserPanel, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        chooserPanel.setOpaque(true);
        chooserPanel.setBackground(new Color(255, 0, 255));
    }
    chooserPanel.add(unitChooser);
    chooserPanel.add(Box.createHorizontalStrut(100));

    //Put everything together.
    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
    add(unitGroup);
    add(chooserPanel);
    unitGroup.setAlignmentY(TOP_ALIGNMENT);
    chooserPanel.setAlignmentY(TOP_ALIGNMENT);
}

From source file:FormatterFactoryDemo.java

public FormatterFactoryDemo() {
    super(new BorderLayout());
    setUpFormats();//from  ww w  . ja v  a2  s. c om
    double payment = computePayment(amount, rate, numPeriods);

    //Create the labels.
    amountLabel = new JLabel(amountString);
    rateLabel = new JLabel(rateString);
    numPeriodsLabel = new JLabel(numPeriodsString);
    paymentLabel = new JLabel(paymentString);

    //Create the text fields and set them up.
    amountField = new JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(amountDisplayFormat),
            new NumberFormatter(amountDisplayFormat), new NumberFormatter(amountEditFormat)));
    amountField.setValue(new Double(amount));
    amountField.setColumns(10);
    amountField.addPropertyChangeListener("value", this);

    NumberFormatter percentEditFormatter = new NumberFormatter(percentEditFormat) {
        public String valueToString(Object o) throws ParseException {
            Number number = (Number) o;
            if (number != null) {
                double d = number.doubleValue() * 100.0;
                number = new Double(d);
            }
            return super.valueToString(number);
        }

        public Object stringToValue(String s) throws ParseException {
            Number number = (Number) super.stringToValue(s);
            if (number != null) {
                double d = number.doubleValue() / 100.0;
                number = new Double(d);
            }
            return number;
        }
    };
    rateField = new JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(percentDisplayFormat),
            new NumberFormatter(percentDisplayFormat), percentEditFormatter));
    rateField.setValue(new Double(rate));
    rateField.setColumns(10);
    rateField.addPropertyChangeListener("value", this);

    numPeriodsField = new JFormattedTextField();
    numPeriodsField.setValue(new Integer(numPeriods));
    numPeriodsField.setColumns(10);
    numPeriodsField.addPropertyChangeListener("value", this);

    paymentField = new JFormattedTextField(paymentFormat);
    paymentField.setValue(new Double(payment));
    paymentField.setColumns(10);
    paymentField.setEditable(false);
    paymentField.setForeground(Color.red);

    //Tell accessibility tools about label/textfield pairs.
    amountLabel.setLabelFor(amountField);
    rateLabel.setLabelFor(rateField);
    numPeriodsLabel.setLabelFor(numPeriodsField);
    paymentLabel.setLabelFor(paymentField);

    //Lay out the labels in a panel.
    JPanel labelPane = new JPanel(new GridLayout(0, 1));
    labelPane.add(amountLabel);
    labelPane.add(rateLabel);
    labelPane.add(numPeriodsLabel);
    labelPane.add(paymentLabel);

    //Layout the text fields in a panel.
    JPanel fieldPane = new JPanel(new GridLayout(0, 1));
    fieldPane.add(amountField);
    fieldPane.add(rateField);
    fieldPane.add(numPeriodsField);
    fieldPane.add(paymentField);

    //Put the panels in this panel, labels on left,
    //text fields on right.
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    add(labelPane, BorderLayout.CENTER);
    add(fieldPane, BorderLayout.LINE_END);
}

From source file:dbseer.gui.panel.DBSeerMiddlewarePanel.java

private void initializeGUI() {
    this.setLayout(new MigLayout());

    JLabel ipAddressLabel = new JLabel("IP Address:");
    JLabel portLabel = new JLabel("Port:");
    JLabel idLabel = new JLabel("ID:");
    JLabel passwordLabel = new JLabel("Password:");

    ipField = new JTextField(20);

    DecimalFormat portFormatter = new DecimalFormat();

    portFormatter.setMaximumFractionDigits(0);
    portFormatter.setMaximumIntegerDigits(5);
    portFormatter.setMinimumIntegerDigits(1);
    portFormatter.setDecimalSeparatorAlwaysShown(false);
    portFormatter.setGroupingUsed(false);

    portField = new JFormattedTextField(portFormatter);
    portField.setColumns(6);/*w  ww.  j a v  a 2 s .com*/
    portField.setText("3555"); // default port.
    idField = new JTextField(20);
    passwordField = new JPasswordField(20);

    logInOutButton = new JButton("Login");
    logInOutButton.addActionListener(this);
    startMonitoringButton = new JButton("Start Monitoring");
    startMonitoringButton.addActionListener(this);
    stopMonitoringButton = new JButton("Stop Monitoring");
    stopMonitoringButton.addActionListener(this);

    startMonitoringButton.setEnabled(true);
    stopMonitoringButton.setEnabled(false);

    ipField.setText(DBSeerGUI.userSettings.getLastMiddlewareIP());
    portField.setText(String.valueOf(DBSeerGUI.userSettings.getLastMiddlewarePort()));
    idField.setText(DBSeerGUI.userSettings.getLastMiddlewareID());

    NumberFormatter formatter = new NumberFormatter(NumberFormat.getIntegerInstance());
    formatter.setMinimum(1);
    formatter.setMaximum(120);
    formatter.setAllowsInvalid(false);

    refreshRateLabel = new JLabel("Monitoring Refresh Rate:");
    refreshRateField = new JFormattedTextField(formatter);
    JLabel refreshRateRangeLabel = new JLabel("(1~120 sec)");

    refreshRateField.setText("1");
    applyRefreshRateButton = new JButton("Apply");
    applyRefreshRateButton.addActionListener(this);

    this.add(ipAddressLabel, "cell 0 0 2 1, split 4");
    this.add(ipField);
    this.add(portLabel);
    this.add(portField);
    this.add(idLabel, "cell 0 2");
    this.add(idField, "cell 1 2");
    this.add(passwordLabel, "cell 0 3");
    this.add(passwordField, "cell 1 3");
    this.add(refreshRateLabel, "cell 0 4");
    this.add(refreshRateField, "cell 1 4, growx, split 3");
    this.add(refreshRateRangeLabel);
    this.add(applyRefreshRateButton, "growx, wrap");
    //      this.add(logInOutButton, "cell 0 2 2 1, growx, split 3");
    this.add(startMonitoringButton);
    this.add(stopMonitoringButton);
}

From source file:com.jgoodies.validation.tutorial.formatted.NumberExample.java

/**
 * Appends the demo rows to the given builder and returns the List of
 * formatted text fields./*  w  w  w .  j a  v a  2 s .  c  om*/
 * 
 * @param builder  the builder used to add components to
 * @return the List of formatted text fields
 */
private List appendDemoRows(DefaultFormBuilder builder) {
    // The Formatter is choosen by the initial value.
    JFormattedTextField defaultNumberField = new JFormattedTextField(new Long(42));

    // The Formatter is choosen by the given Format.
    JFormattedTextField noInitialValueField = new JFormattedTextField(NumberFormat.getIntegerInstance());

    // Uses a custom NumberFormat.
    NumberFormat customFormat = NumberFormat.getIntegerInstance();
    customFormat.setMinimumIntegerDigits(3);
    JFormattedTextField customFormatField = new JFormattedTextField(new NumberFormatter(customFormat));

    // Uses a custom NumberFormatter that prints natural language strings.
    JFormattedTextField customFormatterField = new JFormattedTextField(new CustomNumberFormatter());

    // Uses a custom FormatterFactory that used different formatters
    // for the display and while editing.
    DefaultFormatterFactory formatterFactory = new DefaultFormatterFactory(new NumberFormatter(),
            new CustomNumberFormatter());
    JFormattedTextField formatterFactoryField = new JFormattedTextField(formatterFactory);

    // Wraps a NumberFormatter to map empty strings to null and vice versa.
    JFormattedTextField numberOrNullField = new JFormattedTextField(new EmptyNumberFormatter());

    // Wraps a NumberFormatter to map empty strings to -1 and vice versa.
    Integer emptyValue = new Integer(-1);
    JFormattedTextField numberOrEmptyValueField = new JFormattedTextField(new EmptyNumberFormatter(emptyValue));
    numberOrEmptyValueField.setValue(emptyValue);

    // Commits values on valid edit texts.
    DefaultFormatter formatter = new NumberFormatter();
    formatter.setCommitsOnValidEdit(true);
    JFormattedTextField commitOnValidEditField = new JFormattedTextField(formatter);

    // Returns number values of type Integer
    NumberFormatter numberFormatter = new NumberFormatter();
    numberFormatter.setValueClass(Integer.class);
    JFormattedTextField integerField = new JFormattedTextField(numberFormatter);

    Format displayFormat = new DisplayFormat(NumberFormat.getIntegerInstance());
    Format typedDisplayFormat = new DisplayFormat(NumberFormat.getIntegerInstance(), true);
    List fields = new LinkedList();
    fields.add(Utils.appendRow(builder, "Default", defaultNumberField, typedDisplayFormat));
    fields.add(Utils.appendRow(builder, "No initial value", noInitialValueField, displayFormat));
    fields.add(Utils.appendRow(builder, "Empty <-> null", numberOrNullField, displayFormat));
    fields.add(Utils.appendRow(builder, "Empty <->   -1", numberOrEmptyValueField, displayFormat));
    fields.add(Utils.appendRow(builder, "Custom format", customFormatField, displayFormat));
    fields.add(Utils.appendRow(builder, "Custom formatter", customFormatterField, displayFormat));
    fields.add(Utils.appendRow(builder, "Formatter factory", formatterFactoryField, displayFormat));
    fields.add(Utils.appendRow(builder, "Commits on valid edit", commitOnValidEditField, displayFormat));
    fields.add(Utils.appendRow(builder, "Integer Result", integerField, typedDisplayFormat));

    return fields;
}