1
  1. Have a jtextfield in my java form. I want to not allow to type alpha(Characters) and only allow to type numbers.

  2. And can't type 2 decimal point and two numbers after the decimal point.(that jtextfield for price..)

Please tell me how to do this step by step.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Gayan Weerakkodi
  • 11
  • 1
  • 1
  • 2

3 Answers3

5

Please tell me how to do this step by step.

  1. use JFormattedTextField with NumberFormatter

    • restrict number of decimal places

    • set various RoundingModes

    • restrict range, set minimal and/or maximal value

  2. another of ways is to use JSpinner with SPinnerNUmberModel, but required to use DocumentFilter

for example

import java.awt.*;
import java.awt.font.TextAttribute;
import java.math.*;
import java.text.*;
import java.util.Map;
import javax.swing.*;
import javax.swing.JFormattedTextField.*;
import javax.swing.event.*;
import javax.swing.text.InternationalFormatter;

public class DocumentListenerAdapter {

    public DocumentListenerAdapter() {
        JFrame frame = new JFrame("AbstractTextField Test");
        final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
        textField1.setFormatterFactory(new AbstractFormatterFactory() {
            @Override
            public AbstractFormatter getFormatter(JFormattedTextField tf) {
                NumberFormat format = DecimalFormat.getInstance();
                format.setMinimumFractionDigits(2);
                format.setMaximumFractionDigits(2);
                format.setRoundingMode(RoundingMode.HALF_UP);
                InternationalFormatter formatter = new InternationalFormatter(format);
                formatter.setAllowsInvalid(false);
                //formatter.setMinimum(0.0);
                //formatter.setMaximum(1000.00);
                return formatter;
            }
        });
        final Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01));
        textField2.setFormatterFactory(new AbstractFormatterFactory() {
            @Override
            public AbstractFormatter getFormatter(JFormattedTextField tf) {
                NumberFormat format = DecimalFormat.getInstance();
                format.setMinimumFractionDigits(2);
                format.setMaximumFractionDigits(2);
                format.setRoundingMode(RoundingMode.HALF_UP);
                InternationalFormatter formatter = new InternationalFormatter(format);
                formatter.setAllowsInvalid(false);
                //formatter.setMinimum(0.0);
                //formatter.setMaximum(1000.00);
                return formatter;
            }
        });
        textField2.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent documentEvent) {
                printIt(documentEvent);
            }

            @Override
            public void insertUpdate(DocumentEvent documentEvent) {
                printIt(documentEvent);
            }

            @Override
            public void removeUpdate(DocumentEvent documentEvent) {
                printIt(documentEvent);
            }

            private void printIt(DocumentEvent documentEvent) {
                DocumentEvent.EventType type = documentEvent.getType();
                double t1a1 = (((Number) textField2.getValue()).doubleValue());
                if (t1a1 > 1000) {
                    Runnable doRun = new Runnable() {
                        @Override
                        public void run() {
                            textField2.setFont(new Font(attributes));
                            textField2.setForeground(Color.red);
                        }
                    };
                    SwingUtilities.invokeLater(doRun);
                } else {
                    Runnable doRun = new Runnable() {
                        @Override
                        public void run() {
                            textField2.setFont(new Font("Serif", Font.BOLD, 16));
                            textField2.setForeground(Color.black);
                        }
                    };
                    SwingUtilities.invokeLater(doRun);
                }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.NORTH);
        frame.add(textField2, BorderLayout.SOUTH);
        frame.setVisible(true);
        frame.pack();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                DocumentListenerAdapter main = new DocumentListenerAdapter();
            }
        });
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
4

Use JFormattedTextField with NumberFormat (See for example). Alternatively you can add your own DocumentFilter to the document of your JTextField

StanislavL
  • 56,971
  • 9
  • 68
  • 98
1

Try this code if you want only number to be inputed in you textfield

txtfield.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
        if (!((c >= 0) && (c <= 9) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
            getToolkit().beep();
            e.consume();
        }
    }
});

paste the above code in your constructor after txtfield initialization

also take a look at this stuff JFormattedTextField for Double still takes characters

Community
  • 1
  • 1
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • Bad approach. What about pasting wrong content? – StanislavL Aug 07 '13 at 12:14
  • 1
    May I suggest replace `(c >= 0) && (c <= 9)` with `Character.isDigit(c)`? – dic19 Aug 07 '13 at 12:17
  • 1
    -1 Many problems with this approach. What about decimal points or negative signs (but not multiples of either, and they must be in a logical place)? – splungebob Aug 07 '13 at 13:16
  • I leaving this thread for whales, JFormattedTextField with NumberFormatter is the same as JTextField with DocumentFilter, issue is only with JSpinner (Editor is JTextField) with SpinnerNumberModel, there is required to add DocumentListener – mKorbel Aug 07 '13 at 13:31