java - Try-Catch block 获取字符串长度错误

标签 java try-catch

我一切正常,但 JTextField 遇到问题。当用户未提交任何内容时,它应该返回 null 而不是 0。到目前为止它返回 0,但我需要它返回 NULL。即使我输入了 System.out.println("test"); 它也根本没有到达 Catch block 。

import javax.swing.*;
import javax.*;
import javax.swing.JFrame;

import java.awt.*;
import java.awt.event.*;


public class stringlength implements ActionListener {

  public static JLabel outputLabel;
  public static JTextField inputField = new JTextField(20);

  public static void main(String[] args) {

    stringlength myWindow = new stringlength ();

  }

  public stringlength (){
    JFrame frame = new JFrame("stringlength");
    frame.setVisible(true);
    frame.setSize(500,100);
    //frame.setLayout(new GridLayout(1,3));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    frame.add(panel);

    outputLabel = new JLabel("String length = ");
    JButton stringLengthButton = new JButton("Get String Length");
    stringLengthButton.addActionListener(this);


    panel.add(stringLengthButton);
    panel.add(outputLabel);
    panel.add(inputField);

  }


  public void actionPerformed(ActionEvent e) {

    try{
    String text = inputField.getText();
    System.out.println(text);
    outputLabel.setText("String length = " + text.length());
    }
    catch(NullPointerException e1)
    {
        e1.printStackTrace();

    }
  }

}

最佳答案

getText() 永远不会返回 null。如果您想要 null 值或异常,则必须检测零长度字符串并返回 null 或自行引发异常。

JavaDoc for getText()

关于java - Try-Catch block 获取字符串长度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013487/

相关文章:

java - 何时在 Java 中使用 switch 语句

java - java异常的catch block 中是否会捕获断言错误?

php - Zend 在我之前捕获所有异常?

独立类的 Java ActionListener

java - 我有 5 个字符串,有些正在动态变化,但有些不能

java - 在 IntelliJ IDEA 中调试时无法使用 lambda 作为断点条件

java - 在 try block 中返回一个字符串

java - 为什么 "try"方法的 "Try/Catch"部分中的 boolean 值是?

c# - ServiceBase.Run,​​为什么我不能捕获它的异常或以其他方式对它们使用react?

java - 尝试不要在 while(true) 循环中执行多次