简体   繁体   English

在单击按钮时执行JTextField验证会引发NullPointerException

[英]Performing JTextField validation on button click throws NullPointerException

I would like to validate few text fields on button click. 我想验证按钮单击时的几个文本字段。

The main concept is to let user input few numbers in few text fields and when he clicks a button to run some method to validate inputs. 主要概念是让用户在几个文本字段中输入几个数字,以及当他单击按钮以运行某种方法来验证输入时。

  • Check if there are only numbers in textfields. 检查文本字段中是否只有数字。
  • Check if there is duplicate numbers in textfields. 检查文本字段中是否有重复的数字。
  • Check if all 6 fields contain some value. 检查所有6个字段是否都包含某个值。
  • Check if numbers are in range 1-100 检查数字是否在1-100的范围内

I would like to run validation on button click 我想在单击按钮时运行验证

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

} 

These are textfields I would like to validate: 这些是我要验证的文本字段:

private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;  

I have found some piece of code online but I can't seem to get it working. 我在网上找到了一些代码,但似乎无法正常工作。 Here is the code: 这是代码:

JTextField[] fields;

void validation() { //call when appropriate(ie ActionListener of JButton)     
    System.out.println( "Called validation!");
    int[] nums = new int[fields.length];
    Set<Integer> set = new HashSet<>();
    System.out.println( "Called validation!" + nums);

    for (int i = 0; i < fields.length; i++) {            
        try {
            nums[i] = Integer.parseInt(fields[i].getText());
        } catch (NumberFormatException ex) {
            //not a valid number tell user of error
            JOptionPane.showMessageDialog(null,"Not a valid format");
            return;
        }

        if (nums[i] < 1 || nums[i] > 48) {
            //out of number range tell user of error
            JOptionPane.showMessageDialog(null,"Range error");
            return;
        }

        if (!set.add(nums[i])) {
            //duplicate element tell user of error
            JOptionPane.showMessageDialog(null,"Duplicate");
            return;
        }
    }

    JOptionPane.showMessageDialog(null,"A, OK");
}

How can i make this method to work on buton click. 我如何才能使此方法在单击时起作用。 When i run this method netbeans shows error: 当我运行此方法时,netbeans显示错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException...

You could try this code: 您可以尝试以下代码:

try{
    int nums[] = new int[6];
    nums[0] = Integer.parseInt(jTextField1.getText());
    nums[1] = Integer.parseInt(jTextField2.getText());
    nums[2] = Integer.parseInt(jTextField3.getText());
    nums[3] = Integer.parseInt(jTextField4.getText());
    nums[4] = Integer.parseInt(jTextField5.getText());
    nums[5] = Integer.parseInt(jTextField6.getText());
} catch (NumberFormatException e){
    System.out.println("Some field does not contain a number");
    return;
}

for(int i=0; i<5; i++){
    if(nums[i]==nums[i+1]){
        System.out.println("Repeated number");
        return;
    }
}

For floating point numbers: Float.parseFloat(); 对于浮点数:Float.parseFloat();

At this line: 在这一行:

int[] nums = new int[fields.length];

Based on your code it seems fields is never initialized and consequently you get a NPE. 根据您的代码,似乎从未初始化fields ,因此您得到了NPE。

Some tips 一些技巧

These requirement: 这些要求:

  • Check if there are only numbers in textfields. 检查文本字段中是否只有数字。
  • Check if all 6 fields contain some value. 检查所有6个字段是否都包含某个值。
  • Check if numbers are in range 1-100 检查数字是否在1-100的范围内

Can be easily accomplished by using formatted text fields or spinners instead of plain text fields. 使用格式化的文本字段或微调框而不是纯文本字段可以轻松完成。 By using one of these you won't have to care about parsing strings since you can make users have input restricted to integers. 通过使用其中之一,您将不必担心解析字符串,因为您可以使用户的输入限制为整数。 You can also give them a default value so all of them will have a value. 您还可以为它们提供一个默认值,以便所有它们都具有一个值。 And finally you can set an allowed range of values. 最后,您可以设置一个允许的值范围。

Take a look to How to Use Formatted Text Fields and How to Use Spinners tutorials. 看看如何使用带格式的文本字段如何使用微调器教程。

This other requirements: 这其他要求:

  • Check if there is duplicate numbers in textfields. 检查文本字段中是否有重复的数字。

Can be done by iterating over the formatted text fields or spinners, requesting their values and validating those conditions. 可以通过遍历格式化的文本字段或微调器,请求其值并验证那些条件来完成。

Example

This example is based on formatted text fields but it can also be accomplished with spinners. 本示例基于带格式的文本字段,但也可以使用微调框来完成。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.text.NumberFormatter;

public class Demo {

    private void createAndShowGUI() {

        NumberFormat  format = NumberFormat.getInstance();
        format.setParseIntegerOnly(true);

        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setMinimum(1);
        formatter.setMaximum(100);
        formatter.setAllowsInvalid(false);
        formatter.setOverwriteMode(true);        

        final JPanel gridPanel = new JPanel(new GridLayout(2, 3));

        for (int i = 0; i < 6; i++) {
            JFormattedTextField textField = new JFormattedTextField(formatter);
            textField.setColumns(5);
            textField.setValue(1);
            gridPanel.add(textField);
        }

        JButton button = new JButton("Validate");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List list = new ArrayList();
                for(Component comp : gridPanel.getComponents()) {
                    JFormattedTextField textField = (JFormattedTextField)comp;
                    Integer value = (Integer)textField.getValue();
                    Color foreground = list.contains(value) ? Color.RED : Color.BLACK;
                    textField.setForeground(foreground);
                    list.add(value);
                }
            }
        });

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(gridPanel, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM