代碼的用途:創建兩個按鈕(button1和button2)。當用戶單擊按鈕1時,更改按鈕2的文本。當用戶單擊按鈕2時,更改button1的文本。運行多個Action事件時出現NullPointerException
下面是我使用的代碼:它編譯完美
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)如何追蹤運行時錯誤?
文件名後的數字爲您的實際行,其中錯誤順便說一下,發生了。 – Gnoupi 2010-07-12 10:01:28
請參見「命名規則」 - http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html 「類名應爲名詞,大小寫一致,每個內部單詞的首字母大寫。儘量保持你的類名簡單和描述性。使用整個單詞 - 避免首字母縮略詞和縮寫。「 – 2010-07-12 10:05:44
下次我會記住這一點。 – MoonStruckHorrors 2010-07-12 10:09:44