代码的目的:创建两个按钮(按钮 1 和按钮 2)。当用户单击 button1 时,更改 button2 的文本。当用户单击 button2 时,更改 button1 的文本。
这是我正在使用的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class multiAL {
JButton button1;
JButton button2;
JFrame frame;
public static void main(String[] args) {
multiAL setterAL = new multiAL();
setterAL.go();
}
public void go() {
button1 = new JButton("Click me, I'm One");
button2 = new JButton("Click me, I'm Two");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.WEST, button1);
frame.getContentPane().add(BorderLayout.EAST, button2);
frame.setVisible(true);
button1.addActionListener(new b1L());
button2.addActionListener(new b2L());
}
class b1L implements ActionListener {
public void actionPerformed(ActionEvent event) {
button2.setText("What??, you clicked 1??");
}
}
class b2L implements ActionListener {
public void actionPerformed(ActionEvent event) {
button1.setText("What??, you clicked 2??");
}
}
}
它编译得很好,但是当我运行它时,我收到以下错误:
Exception in thread "main" java.lang.NullPointerException
at multiAL.go(multiAL.java:17)
at multiAL.main(multiAL.java:11)
到目前为止,我只遇到过编译时错误。所以有两个问题我想问:
1)代码有什么问题?2)如何追踪运行时错误?