Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();
        JTextField tField = new JTextField(10);
        ((AbstractDocument) tField.getDocument()).setDocumentFilter(new MyDocumentFilter());
        contentPane.add(tField);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setVisible(true);
    }
}

class MyDocumentFilter extends DocumentFilter {
    @Override
    public void insertString(DocumentFilter.FilterBypass fp, int offset, String string, AttributeSet aset)
            throws BadLocationException {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++) {
            if (!Character.isDigit(string.charAt(i))) {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger) {
            super.insertString(fp, offset, string, aset);
        } else {
            System.out.println("not valid integer");
        }
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fp, int offset, int length, String string, AttributeSet aset)
            throws BadLocationException {
        int len = string.length();
        boolean isValidInteger = true;
        for (int i = 0; i < len; i++) {
            if (!Character.isDigit(string.charAt(i))) {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger) {
            super.replace(fp, offset, length, string, aset);
        } else {
            System.out.println("not valid integer");
        }
    }
}