仅限数字限制JTextField

时间:2014-01-25 20:23:11

标签: java swing jframe

我正在制作一个小应用,我有两个文本字段。但我希望它是当用户插入不是数字的东西时,它会发出警告信息。我已经像下面这样做但它不起作用。我试过用try&抓住。任何人都可以帮我这个吗?

public void actionPerformed(ActionEvent ngjarja)
{
    String rresht = teksti1.getText(); 
    int rreshtii = Integer.parseInt(rresht);//kthimi i stringut ne integer
    String shtyll = teksti2.getText();
    int shtylle = Integer.parseInt(shtyll);

    if (ngjarja.getSource()== mat)
    mbushMatricenString(rreshtii,shtylle);  //Thirr metoden  

    if (ngjarja.getSource()== buton1)
     mbushVektorinString1( rreshtii,shtylle);

    try { Integer.parseInt(teksti1.getText());
    Integer.parseInt(teksti2.getText());


    } catch (NumberFormatException e) {
        JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
    }


}  

3 个答案:

答案 0 :(得分:2)

问题是ActionListener只会在用户“操作”字段时调用(通常按 Enter

你可以......

使用InputVerfier可以验证字段的状态。

请查看Validting Input了解更多详情......

你可以......

使用DocumentFilter实际阻止用户输入您不想要的任何内容。

请查看Implementing a Document FilterMDP's Weblog示例......

你可以......

使用JSpinner代替

答案 1 :(得分:1)

看一下这个例子,它只接受来自用户的号码,并在JOptionPane中显示相应的错误信息。

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class Test {

    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField jtf = new JTextField();
        //add filter to document
        ((AbstractDocument) jtf.getDocument()).setDocumentFilter(new MyDocumentFilter());

        frame.add(jtf);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class MyDocumentFilter extends DocumentFilter {

    @Override
    public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
        for (int n = string.length(); n > 0; n--) {//an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want
            char c = string.charAt(n - 1);//get a single character of the string
            System.out.println(c);
            if (Character.isDigit(c)) {//if its an alphabetic character or white space
                super.replace(fb, i, i1, String.valueOf(c), as);//allow update to take place for the given character
            } else {//it was not an alphabetic character or white space
                System.out.println("Not allowed");
                JOptionPane.showMessageDialog(null, "Only Numbers are allowed");
            }
        }
    }

    @Override
    public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
        super.remove(fb, i, i1);
    }

    @Override
    public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
        super.insertString(fb, i, string, as);

    }
}

答案 2 :(得分:0)

使用此:

([1-9][0-9]+|[2-9])