Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at A_test.addButton(A_test.java:27)
at A_test.<init>(A_test.java:17)
at Main$1.run(Main.java:11)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
import javax.swing.*;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new A_test();
}
});
}
}
A_test類
import java.awt.event.*;
import javax.swing.*;
public class A_test implements ActionListener {
private JFrame jf;
public A_test() {
JFrame jf = new JFrame("A simple swing Program");
jf.setSize(275,100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jl = new JLabel("Swing powers the modern JAVA GUI");
jf.getContentPane().add(jl);
this.addButton();
jf.setVisible(true);
}
public void addButton() {
JButton jb = new JButton("Submit");
jf.getContentPane().add(jb);
jb.addActionListener(this);
jf.getContentPane().add(jb);
}
@Override
public void actionPerformed(ActionEvent ae) {
((JLabel) jf.getContentPane().getComponent(0)).setText("test");
}
}
我使用A_test類,以創建一個標籤,並在它的按鈕的JFrame。當我按下按鈕時,我希望應用程序將標籤的文本從之前的版本更改爲「測試」。
哪一條是第27行? – Tudor
@Tudor jf.getContentPane()。add(jb); – DaveJohnston