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。当我按下按钮时,我希望应用程序将标签的文本从以前的内容更改为“测试”。

最佳答案

这里

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);


您正在创建新的JFrame,而不是将私有实例变量分配给新的JFrame。
在您达到这一点时:

  JButton jb = new JButton("Submit");
jf.getContentPane().add(jb);
jb.addActionListener(this);
jf.getContentPane().add(jb);


jf仍然为空;

只是这样做:

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();

09-25 21:43