JTextfield只接受0-255之间的数字

时间:2016-10-14 08:07:56

标签: java swing validation document

对于一个小测试应用程序我需要一个只接受数字的TextField。此外,用户应该只能输入0-255之间的数字。到目前为止我发现了这个:

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

/**
 * A JTextField that accepts only integers.
 *
 * @author David Buzatto
 */
public class IntegerField extends JTextField {

    public IntegerField() {
        super();
    }

    public IntegerField( int cols ) {
        super( cols );
    }

    @Override
    protected Document createDefaultModel() {
        return new UpperCaseDocument();
    }

    static class UpperCaseDocument extends PlainDocument {

        @Override
        public void insertString( int offs, String str, AttributeSet a )
                throws BadLocationException {

            if ( str == null ) {
                return;
            }

            char[] chars = str.toCharArray();
            boolean ok = true;

            for ( int i = 0; i < chars.length; i++ ) {

                try {
                    Integer.parseInt( String.valueOf( chars[i] ) );
                } catch ( NumberFormatException exc ) {
                    ok = false;
                    break;
                }
            }

            if ( ok ) {
                super.insertString( offs, new String( chars ), a );
            }
        }
    }

我在for循环中添加了以下内容,因此只能输入包含3位数的数字

    if(super.getLength() == 3) {
        ok = false;
        System.out.println("tooLong");
        break;

    }

但是如何设置最大输入值?用户只应输入0-255之间的数字。

提前致谢

3 个答案:

答案 0 :(得分:0)

您可以按如下方式实施这两项检查:

        if(str.length()>3) {
             return;
        } 

        int inputNum = Integer.parseInt(str);
        if(inputNum<0 || inputNum>255) {
             return;
        }   

在最后一个if块之前添加这些检查,你应该好好去。

答案 1 :(得分:0)

这是做你想做的最简单的方法。

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class ByteField extends JTextField {

    private boolean revert;

    @Override
    public void replaceSelection(String content) {
        if (revert) {
            super.replaceSelection(content);
        } else {
            String current = getText();
            super.replaceSelection(content);
            String now = getText();
            try {
                if (!now.isEmpty()) {
                    int val = Integer.valueOf(now);
                    revert = val < 0 || val > 255;
                }
            } catch (Exception e) {
                revert = true;
            }
            if (revert) {
                setText(current);
            }
            revert = false;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JTextField fld = new ByteField();
                fld.setColumns(5);
                JFrame frm = new JFrame("Test");
                frm.add(fld);
                frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frm.pack();
                frm.setLocationRelativeTo(null);
                frm.setVisible(true);
            }
        });
    }
}

以下是使用该文档的方式:

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class ByteField extends JTextField {

    private static class ByteDocument extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            String currText = getText(0, getLength());
            StringBuilder b = new StringBuilder(currText);
            b.insert(offs, str);
            currText = b.toString();
            boolean proceed = true;
            try {
                if (!currText.isEmpty()) {
                    int val = Integer.valueOf(currText);
                    proceed = val >= 0 && val <= 255;
                }
            } catch (Exception e) {
                proceed = false;
            }
            if (proceed) {
                super.insertString(offs, str, a);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JTextField fld = new JTextField(new ByteDocument(), "", 5);
                JFrame frm = new JFrame("Test");
                frm.add(fld);
                frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frm.pack();
                frm.setLocationRelativeTo(null);
                frm.setVisible(true);
            }
        });
    }
}

答案 2 :(得分:0)

这将完成工作,虽然我建议你添加一个catch如果没有任何东西进入textInput就会得到一个空的警告。

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;`
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class Matches extends JFrame{

    JTextArea textInput = new JTextArea(1, 10);
    JLabel labelInput = new JLabel("Enter a number between 0-255");
    JLabel labelOutput = new JLabel();
    JPanel p1 = new JPanel();
    JButton b1 = new JButton("Test Number");


    public Matches () {
        p1.add(labelInput);
        p1.add(textInput);
        p1.add(b1);
        p1.add(labelOutput);
        b1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int answer = Integer.parseInt(textInput.getText());

                if (answer >= 0 && answer <= 255) {
                    labelOutput.setText("You entered: " + textInput.getText());
                } else {
                    JOptionPane.showMessageDialog(null, "Error!, only numbers between 0-255 are allowed!");
                }

            }
        });

        add(p1);
        setVisible(true);
        setSize(300, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

   public static void main(String[] args) {

      new Matches();
   }
}