出于某种原因,我在'if'语句中检查字符串长度时收到NullPointerException。我可能做错了,但我不知道。我试图写的代码基本上只是改变按钮的标签,但只有当字符串'label1'为0个字符长(或未设置)时,才能更改一次。检查字符串长度是否返回NullPointerException?
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);
}
}
您从未初始化'label1'字符串。 –
使用前初始化你的label1 it.public static String label1 = null; –