A textbox class only accept integers in Java

2019-07-18 06:27发布

问题:

I just want to do a textbox class only accepts integers..

I have done something, but ı think it's not enough.

Can anyone help me, please? Thanks...

import java.awt.TextField
public class textbox extends TextField{
    private int value;

    public textbox(){
        super();

    }

    public textbox(int value){
        setDeger(value);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {

        this.value = value;
    }
}

回答1:

I think you are missing the point here's a hint, with your code i can still call textfield.setText("i'm not a number");



回答2:

Since you must use TextArea, you might have some success with a TextListener. Add a listener that restricts the characters entered to just numbers.

In pseudo code the event method could do this:

  1. get event source
  2. determine current cursor position
  3. if the character at the current position is not valid input, then
    1. remove the bad character
    2. reset the text in the field

This is easier to do with a JTextField as you can replace the document model or just use a JFormattedTextField.



回答3:

Why are you using a TextField? Why don't you learn Swing instead of AWT, then you can use a JTextField. Actually you can use a JFormattedTextField which support this requirement. Read the API and follow the link to the tutorial for examples.



回答4:

When user try to enter non-numeric data, it rejects an deletes the input that is not an integer.

public class NumericTextField extends JTextField implements KeyListener{

    private int value;

    public NumericTextField(int value) {
        super(value+ "");
        this.addKeyListener(this);
    }
    public NumericTextField() {
        super();
        this.addKeyListener(this);
    }
    public Object getValue() {
        return value;
    }

    public void setText(int value) {
        super.setText(value + "");
        this.value = value;
    }

    @Override
    public void keyPressed(KeyEvent evt) {
    }
    @Override
    public void keyReleased(KeyEvent arg0) {
        isValidChar(arg0.getKeyChar());
    }
    @Override
    public void keyTyped(KeyEvent arg0) {
    }

     //it is not good solution but acceptable
    private void isValidChar(char ch){
        if(this.getText().length() == 1 && this.getText().equals("-") ){
            this.setText("-");
        }
        else {
            if(!isNumeric(Character.toString(ch))){
                try{
                    this.setText(removeNonnumericChar(this.getText(), ch));
                }catch(Exception e){
                }
            }
        }
    }

    private boolean isNumeric(String text) {
        try {
            Integer.parseInt(text);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    //remove nonnumeric character
    private String removeNonnumericChar(String text, char ch){
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            if(text.charAt(i) != ch){
                sBuilder.append(text.charAt(i));
            }
        }
        return sBuilder.toString();
    }
}

And this is the test class

public class NumericTextFieldTest extends JFrame {

    private JPanel contentPane;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    NumericTextFieldTest frame = new NumericTextFieldTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public NumericTextFieldTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 200, 150);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        NumericTextField numericText = new NumericTextField();
        numericText.setBounds(25, 27, 158, 19);
        contentPane.add(numericText);
        numericText.setColumns(10);

        JLabel lblNumericTextfield = new JLabel("Numeric textField");
        lblNumericTextfield.setBounds(37, 12, 123, 15);
        contentPane.add(lblNumericTextfield);

    }
}