Я попытался использовать показанный пример здесь но java показывает сообщение об ошибке
«AttributeSet не может быть преобразован в тип»
Вот почему я пытаюсь использовать другой метод, разрешающий только цифры:
txtUsername.addKeyListener(new MyKeyListener());
public class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent ke){
System.out.println("Key pressed code = "+ke.getKeyCode());
if (ke.getKeyCode()>=48 && ke.getKeyCode()<=57)
return true;
else
return false;
}
}
Но, конечно, он не работает, потому что keyPressed
метод void
. Итак, что делать, чтобы печатать только цифры в текстовом поле?
Моя версия, которая отклоняет нежелательные символы полностью (я попробовал):
val2 = new JTextField();
val2.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
try {
char input = e.getKeyChar(); //checks each key pressed
// in other words it prevents input of any character other than 0-9 or .
try {
int i = Integer.parseInt(val2.getText());
valid1.setText(""); //valid1 is a label for the message
} catch (Exception e2) {
// TODO: handle exception
valid1.setText("Invalid Number!");
}
if((!Character.isDigit(input)) && !(input == '.')) { //numbers accept "."
e.consume();
// event won't be sent for any further event listeners
try {
int i = Integer.parseInt(val2.getText()); // checks if the string can be converted to int
double i1 = Double.parseDouble(val2.getText()); // checks if string can be converted to double
valid1.setText("");
} catch (Exception e2) {
// TODO: handle exception
// if it is not in a valid format.. it will generate error message
valid1.setText("Invalid Number!");
}
}
else {
// if format and characters are fine... no output
valid1.setText("");
}
}
catch (Exception e2) {
// TODO: handle exception
// for unexpected errors
valid1.setText("Error");
}
}
});
// auto generated for design of the textfield
val2.setColumns(10);
val2.setBounds(236, 11, 126, 43);
panel.add(val2);