Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number input JTextField

I'm working on a sudoku solver and I'm trying to limit the amount of numbers a user can enter into a cell as well as ONLY being able to enter numbers, currently it also accepts letters. At the moment it works like this: If a user enters "11125455876" it will just use the last number entered (in this case "6"). I would like to limit the amount of numbers a user can enter into a single cell to 1 and only accept numbers 1-9. I'm not really sure how I can do that. So maybe it'll just overwrite the previous number or something and if I press a letter key as "a" nothing should happen.

Here is my code:

public PanelGUI(int size) {

    super(size);
    NumberFormat f = NumberFormat.getInstance();
    f.setMaximumIntegerDigits(1);
    f.setMinimumIntegerDigits(0);
    f.setGroupingUsed(false);
    cells = new JTextField[size][size];
    panel.setLayout(new GridLayout(size, size));
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            cells[i][j] = new JFormattedTextField(f);
            cells[i][j].setEditable(true);
            cells[i][j].setFont(boldFont);
            cells[i][j].setBorder(BorderFactory.createMatteBorder(1, 1, 1,
                    1, Color.white));
            cells[i][j].setHorizontalAlignment(JTextField.CENTER);
            panel.add(cells[i][j]);
        }
    }
}

As you can see I'm currently using number format.

like image 738
Rob Avatar asked Oct 22 '22 12:10

Rob


1 Answers

NumberFormat f = NumberFormat.getInstance();
f.setMaximumIntegerDigits(1);
f.setMinimumIntegerDigits(0);
f.setGroupingUsed(false);

You want to use a MaskFormat instread:

MaskFormatter f = new MaskFormatter( "#" );
f.setValidCharacters("123456789");
like image 109
camickr Avatar answered Oct 24 '22 13:10

camickr