java - 如何在没有代码错误的情况下修复 .NullPointerException 错误?
问题描述
很抱歉这篇文章的质量是我第一次在 StackOverflow 上发帖。我正在做我的作业,它包括创建一个银行账户模拟,进行存款和退休,当我完成我的程序时,控制台向我显示:
Exception in thread "main" java.lang.NullPointerException
at java.desktop/java.awt.Container.addImpl(Container.java:1117)
at java.desktop/java.awt.Container.add(Container.java:436)
at Banco.createGUI(Banco.java:29)
at Banco.main(Banco.java:16)
Process finished with exit code 1
这是我的代码,我花了一些时间试图修复它,我找不到值为 null 的变量在哪里,这就是我寻求帮助的原因。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Banco extends JFrame implements ActionListener {
private JLabel label1, label2;
private JTextField Square1, Square2, Square3;
private JButton Button1, Button2;
private Account account;
public static void main(String[] args) {
Banco Ventana = new Banco();
Ventana.setSize(300,300);
Ventana.createGUI();
Ventana.setVisible(true);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
label1 = new JLabel("Balance");
window.add(label1);
Square1 = new JTextField(5);
window.add(Square2);
label2 = new JLabel("State");
window.add(label2);
Square2 = new JTextField(9);
window.add(Square2);
Button1 = new JButton("Deposit");
Button1.addActionListener(this);
window.add(Button1);
Button2 = new JButton("Retire");
Button2.addActionListener(this);
window.add(Button2);
Square3 = new JTextField(5);
window.add(Square3);
account = new Account();
}
public void actionPerformed(ActionEvent event) {
int balance;
int Amount;
balance = account.getBalance();
Amount = Integer.parseInt(Square3.getText());
if(event.getSource() == Button1){
account.setBalance(balance);
account.depositBalance(Amount);
balance = account.getBalance();
}
if (event.getSource() == Button2){
account.setBalance(balance);
account.retireBalance(Amount);
balance = account.getBalance();
}
if (balance < 0){
Square2.setText("Overdrawn");
}
else {
Square2.setText("OK");
}
Square1.setText(Integer.toString(balance));
}
}
class Account{
int Balance=0;
public void setBalance(int Amount){
Balance = Amount;
}
public int getBalance(){
return Balance;
}
public void depositBalance(int Amount){
Balance = Balance + Amount;
}
public void retireBalance(int Amount){
Balance = Balance - Amount;
}
}
解决方案
这看起来很可疑:
Square1 = new JTextField(5);
window.add(Square2);
您初始化Square1
,但尝试添加Square2
到窗口。
推荐阅读
- python - 如何通过pymongo检查文档是否为空?
- google-app-engine - Cloud IAP:如何获取用户资料
- asp.net-mvc - 设计具有多重登录机制的基于云的新应用程序
- python-3.x - python 3.4 shell,为什么需要重新导入相同的模块(永远不要重启shell)
- html - 将无响应图像水平居中
- jquery - 弹出窗口未在 jquery 中的同一按钮单击功能中关闭
- react-native-android - 如何在 android 模拟器中观看而不在 react native 中运行编译命令?
- javascript - 将 json_encode 结果显示到 html 中的输入标签
- json - Comparing json files of array of nested hash in perl
- java - NetworkSecurityConfig:使用资源 network_security_config debugBuild 中的网络安全配置:true