出于某种原因,我在检查“if”语句中的字符串长度时收到 NullPointerException。我可能做错了,但我真的不知道。我尝试编写的代码基本上只是更改按钮的标签,但前提是字符串“label1”的长度为 0 个字符(或未设置),因此它只能更改一次。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Class1 {
public static String label1;
public static String one = ("Hello");
public static String two = ("Goodbye");
public static void main(String args[]) {
JFrame frame = new JFrame();
JPanel pane = new JPanel();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if(label1.length() == 0) {
label1 = one;
JButton button = (JButton) e.getSource();
button.setText(label1);
}
if(label1.length() < 0) {
label1 = two;
JButton button = (JButton) e.getSource();
button.setText(label1);
}
} catch(Exception ex) {
System.out.println("ERROR");
ex.printStackTrace();
}
}
});
frame.setSize(350, 350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
pane.add(button);
}
}
最佳答案
public static String label1;
要使用 if(label1.length() == 0) {
行,您必须在 lable1
之前初始化
你没有初始化标签!任何地方任何人都可以使用它
尝试改变那条线
public static String label="";
或添加额外的空条件
if(label1 != null && label1.length() == 0) {
关于java - 检查字符串长度返回 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17183322/