Ввод определенного количества цифр в JTextField - Java
Формулировка задачи:
Доброго времени суток. У меня есть класс, который не дает вводить ничего кроме цифр и точки в текстовое поле JTextField. Можно ли добавить к этому классу какой-то код, чтобы до точки максимум можно было вводить 2 цифры, а после точки максимум - 3 цифры. То есть например, 2.456, 56.1, 99,999, но например, 234.1, 2.3456 - не можно было вводить.
widthWallField.setDocument(new PlainDocument() {
String chars = "0123456789.";
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (chars.indexOf(str) != -1) {
if (getLength() < 6) {
super.insertString(offs, str, a);
}
}
}
});Решение задачи: «Ввод определенного количества цифр в JTextField»
textual
Листинг программы
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class TestGUI {
public static void main(String[] args) {
//создаём фрэйм
JFrame frame = new JFrame("TestGUI");
frame.setSize(300, 300);
frame.setLayout(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//создаём TextField
JTextField edit = new JTextField();
edit.setBounds(100, 100, 100, 25);
edit.setBackground(Color.pink);
frame.add(edit);
frame.setVisible(true);
edit.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
char key = e.getKeyChar();
int position = edit.getText().length();
if (!isCorrectKey(edit, key, position)) {
e.consume();
}
}
});
}
public static boolean isCorrectKey(JTextField edit, char key, int position) {
int pos = 0;
boolean tochka = false;
String str = edit.getText();
for (int i = 0; i < str.length(); i++){
if (str.charAt(i) == '.') {
tochka = true;
pos = i;
break;
}
}
if (key == '\b') {
return true;
}
if (Character.isDigit(key)) {
if ((pos == 0) && (position >= 0 && position < 2)) return true;
if ((pos == 1) && (position >= 2 && position < 5)) return true;
if ((pos == 2) && (position >= 3 && position < 6)) return true;
}
if (key == '.') {
if ((position == 2 || position == 1) && (tochka == false)) return true;
}
return false;
}
}