Java JFormattedTextField number field for input like "$12,345.67"

Description

Java JFormattedTextField number field for input like "$12,345.67"


import java.awt.FlowLayout;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.NumberFormatter;

public class Main extends JFrame {
  public Main() {
    super("JButton");

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    JLabel nameLabel = new JLabel("Value:");

    NumberFormat numFormat = new DecimalFormat("$#0,000.00");
    NumberFormatter numFormatter = new NumberFormatter(numFormat);
    JFormattedTextField name = new JFormattedTextField(numFormatter);

    name.setValue(new Date());
    JTextField text = new JTextField("Click here to see the validation result");

    getContentPane().add(nameLabel);//from w ww.  j  av a 2s .c o  m
    getContentPane().add(name);
    getContentPane().add(text);

  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related