Make JTextField accept only one digit

1.6k views Asked by At

I'm working on a Sudoku applet, I want to make the cells (extends JTextField) of it so it would accept only integers between 0-9 and length of 1. Later I'll limit it even more (so it would fit the game rules). I started by:

    public Block(int[] blockNum){
        this.setLayout(new GridLayout(3,3));
        this.setBorder(new LineBorder(Color.BLACK,2)); 
        for(int i=0; i<CELL_COUNT; i++){
            cells[i] = new Cell(); // Cell extends JTextField
            ((AbstractDocument)cells[i].getDocument()).setDocumentFilter(
                    new MyDocumentFilter()); // <- this is relevant for this question

            if(blockNum[i]!=0){
                cells[i].setNumber(blockNum[i]);
                cells[i].setEditable(false);
            }
            this.add(cells[i]);
        }
    }
}

Here I'm trying to filter the input, for start I just tried to limit it to integer and one digit, but it seems that I can enter as much digits as I want and the last line is not triggered.

Would like some help here, thank you:

class MyDocumentFilter extends DocumentFilter
{   
    @Override
    public void replace(DocumentFilter.FilterBypass fp, int offset
                    , int length, String string, AttributeSet aset)
                                        throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;
        if (len>1 || !Character.isDigit(string.charAt(0))) isValidInteger = false;


        if (isValidInteger)
            super.replace(fp, offset, length, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }
}
1

There are 1 answers

1
Mike M On BEST ANSWER

Try using the DocumentFilter class. This will allow you to check the input before it is actually shown. You can also edit what I have below to check for only integers.

JTextField tf = new JTextField();
AbstractDocument d = (AbstractDocument) tf.getDocument();
d.setDocumentFilter(new DocumentFilter(){
    int max = 1;

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        int documentLength = fb.getDocument().getLength(); 
            if (documentLength - length + text.length() <= max)
        super.replace(fb, offset, length, text.toUpperCase(), attrs);
    }
});