【问题标题】:JTextfield only accept numbers between 0-255 [duplicate]JTextfield 仅接受 0-255 之间的数字 [重复]
【发布时间】:2016-10-14 08:07:56
【问题描述】:

对于一个小测试应用程序,我需要一个只接受数字的 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 之间的数字。

提前致谢

【问题讨论】:

  • 输入>= 0 && 输入
  • 我知道,但是我应该如何实现这个我从哪里获得/如何获得输入? super.length() 很简单,但我如何制作 super.getInput super.getText?

标签: java swing validation document


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    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);
                }
            });
        }
    }
    

    【讨论】:

    • 请不要使用 DocumentFilter(允许数字),或 JSpinner 或 JFormattedTextField 与 Formatter 中的最小值和最大值
    • @mKorbel 你是对的。有许多方法可以提供所需的功能。 JSpinner/JFormattedTextField 可以让它变得更容易,但它们也有一些限制。
    【解决方案3】:

    这将完成工作,虽然我建议你添加一个 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();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2013-12-30
      • 2012-09-29
      • 1970-01-01
      • 2012-12-28
      相关资源
      最近更新 更多