Java JFormattedTextField number field for integer
import java.awt.FlowLayout; import java.text.NumberFormat; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class Main extends JFrame { public Main() { super("JButton"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); JLabel nameLabel = new JLabel("Value:"); /* w w w . j a v a2s .c o m*/ JFormattedTextField name = new JFormattedTextField(NumberFormat.getIntegerInstance()); name.setValue(new Integer(123)); Integer intValue = (Integer) name.getValue(); System.out.println(intValue); JTextField text = new JTextField("Click here to see the validation result"); getContentPane().add(nameLabel); getContentPane().add(name); getContentPane().add(text); } public static void main(String[] args) { Main frame = new Main(); frame.pack(); frame.setVisible(true); } }
Java JFormattedTextField for integer number
import java.awt.Color; import java.awt.FlowLayout; import java.text.NumberFormat; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.UIManager; 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:"); JFormattedTextField name = createIntegerTextField(0, 100, 10,25); JTextField text = new JTextField("Click here to see the validation result"); getContentPane().add(nameLabel);/*w w w .j a v a2 s .co m*/ getContentPane().add(name); getContentPane().add(text); } 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; } public static void main(String[] args) { Main frame = new Main(); frame.pack(); frame.setVisible(true); } }