Using an if statement to test if JTextField is an integer

青春壹個敷衍的年華 提交于 2019-12-04 06:34:30

问题


I want my program to be able to tell if what is inside my two JTextFields is an integer or a String.

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

                }
            });    

This if statement tests if what is in the JTextField is " Set Height " or " Set Width " but i want them to test if what is in them is a number, how would I do that?

i cant figure out the Integer.ParseInt. Please help.


回答1:


Not sure exactly where in your code the test is being performed, but you can use this method to determine if a String is an integer:

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

Less expensive none exception based way, assuming your code does not need to throw an exception:

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



回答2:


For restricting a User from entering anything but digits, you can set a DocumentFilter on the JTextField.

Here is a small example :

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

Or one can simply use this approach, as given by @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);
}



回答3:


You can process the key event in the action method also. Try this

First make a JTextField

JTextField j=new JTextField();

Then add KeyListner to this JTextField as

    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 is ASCII code for 0 and 57 is ASCII code for 9. You can also ignore virtual keys like shift. See ASCII chart



来源:https://stackoverflow.com/questions/17413204/using-an-if-statement-to-test-if-jtextfield-is-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!