使用if语句测试JTextField是否为整数

时间:2013-07-01 20:34:51

标签: java swing if-statement actionlistener jtextfield

我希望我的程序能够判断我的两个JTextFields中的内容是整数还是字符串。

CODE

          public void actionPerformed(ActionEvent e){
                if(inputH.getText().equals(" Set Height ") || 
                        inputW.getText().equals(" Set Width ")){
          JOptionPane.showMessageDialog(frame,
          "Change Height And Width To A Number.",
          "Change Height To A Number",
          JOptionPane.ERROR_MESSAGE);
                    }                  

                }
            });    

此if语句测试JTextField中的内容是" Set Height "还是" Set Width ",但我希望他们测试其中的内容是否为数字,我该怎么做?

我无法弄清楚Integer.ParseInt。请帮忙。

3 个答案:

答案 0 :(得分:3)

不确定代码中测试的确切位置,但您可以使用此方法确定String是否为整数:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // if exception isn't thrown, then it is an integer
    return true;
}

基于这种方式,不需要基于异常的方法,假设您的代码不需要抛出异常:

public static boolean isInt(String s){
        for(int i = 0; i < s.length(); i++){
            if(!Character.isDigit(s.charAt(i))){
                 return false;
            }
        }
        return true;
}

答案 1 :(得分:2)

要限制用户输入digits以外的任何内容,您可以在JTextField上设置DocumentFilter

这是一个小例子:

import java.awt.*;
import javax.swing.*;
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 InputInteger
{
    private JTextField tField;
    private MyDocumentFilter documentFilter;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Input Integer Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        tField = new JTextField(10);
        ((AbstractDocument)tField.getDocument()).setDocumentFilter(
                new MyDocumentFilter());        
        contentPane.add(tField); 

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                new InputInteger().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class MyDocumentFilter extends DocumentFilter
{   
    @Override
    public void insertString(DocumentFilter.FilterBypass fp
            , int offset, String string, AttributeSet aset)
                                throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.insertString(fp, offset, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fp, int offset
                    , int length, String string, AttributeSet aset)
                                        throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.replace(fp, offset, length, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }
}

或者可以简单地使用这种方法,如@Carlos Heuberger

所给出的
@Override
public void insertString(FilterBypass fb, int off
                     , String str, AttributeSet attr) 
                               throws BadLocationException 
{
    // remove non-digits
    fb.insertString(off, str.replaceAll("\\D++", ""), attr);
} 
@Override
public void replace(FilterBypass fb, int off
      , int len, String str, AttributeSet attr) 
                       throws BadLocationException 
{
    // remove non-digits
    fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
}

答案 2 :(得分:-1)

您也可以使用action方法处理关键事件。试试这个

首先制作JTextField

JTextField j=new JTextField();

然后将KeyListner添加到此JTextField

    j.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub
            if(arg0.getKeyCode()>57 || arg0.getKeyCode()<48) {
                    //your error message and other handling code here
                JOptionPane.showMessageDialog(PatentFrame, "Only integer allowed", "Message title",JOptionPane.ERROR_MESSAGE);
            }

        }

        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
    });

48是0的ASCII码,57是9的ASCII码。你也可以忽略像shift这样的虚拟键。 See ASCII chart