gpt4 book ai didi

java - Java Swing 中的 JButton 错误

转载 作者:行者123 更新时间:2023-12-01 22:15:17 24 4
gpt4 key购买 nike

我正在使用 AppDev(应用程序开发),并且我使用 JFrame 创建了一个 JButton,并带有名称为“Button”的测试按钮,我收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at apptutorial.AppDev.initApp(AppDev.java:18)
at apptutorial.AppDev.<init>(AppDev.java:10)
at apptutorial.AppDev$1.run(AppDev.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:738)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:699)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:708)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

我的文件“AppDev.java”的代码是:

package apptutorial;
import java.awt.*;
import javax.swing.*;

public class AppDev extends JFrame {

public AppDev() {
initApp();
}
/*
This Generated App Code generates a app which has running now.
*/

// <editor-fold defaultstate="collapsed" desc="Generated App Code">
private void initApp() {
frame.setTitle("Alpha Application");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(new JButton("Button"));
frame.setSize(400,350);
frame.setVisible(true);
}
// </editor-fold>

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new AppDev().setVisible(true);
}
});
}
private JFrame frame;
}

谁能修复我以解决错误。

最佳答案

您尚未初始化变量框架

 private void initApp() {
frame=new JFrame();//you missed this
frame.setTitle("Alpha Application");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(new JButton("Button"));
frame.setSize(400,350);
frame.setVisible(true);
}

不知道为什么要在框架内创建框架

但是没有必要这样做,因为您已经将 JFrame 扩展了

public class AppDev extends JFrame

你可以简单地这样做

 private void initApp() {

setTitle("Alpha Application");
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new JButton("Button"));
setSize(400,350);
setVisible(true);
}

关于java - Java Swing 中的 JButton 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com