Reputation: 21
I'm trying to make a bank account into a GUI, but the Buttons don't work because of the setText method. Nothing appear in the textarea.
the Account class
public class Account {
//attribute for balance amount
private double balance;
// constructor to inital the balance attribute
public Account(double nitialBalance){
if(nitialBalance > 0.0)
balance=nitialBalance;
}
// to add money method
public void set_add_Balance(Double balance1){
balance+=balance1;
}
// the withdrawn amount from the account
public void depit(double debit){
double f=0;
balance=balance-debit;
if (balance <= 0){
f=debit;
System.out.println("f=debit");
}
if(balance <= 0){
balance = balance + f;
System.out.println("Debit amount exceeded account balance ");
}
}
// to cheack the amount you have
public double getBalance( ){
return balance;
}
// tostring for get balance
public String toString(){
return "Your Balance is : "+getBalance();
}
}
The GUI method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame {
Account a;
JButton j1=new JButton("Your Balance");
JButton j2=new JButton("Add Money");
JButton j3=new JButton("Withdrow Money");
JButton j4=new JButton("Exit");
TextArea t1=new TextArea("");
Container cont = getContentPane();
public GUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Bank Account");
setSize(500,300);
JPanel p = new JPanel();
p.setLayout(new GridLayout(2,2));
p.add(j1); p.add(j3);
p.add(j2); p.add(j4);
cont.add(p,"South");
cont.add(t1,"Center");
j1.addActionListener(new buttons());
j2.addActionListener(new buttons());
j3.addActionListener(new buttons());
j4.addActionListener(new buttons());
}
private class buttons implements ActionListener {
public void actionPerformed (ActionEvent e){
Object c =e.getSource();
if(c==j1) {
t1.setText( "Your Balance is: "+a.toString());
}
if(c==j2) {
a.set_add_Balance(50.0);
t1.setText( "Your Balance is: "+a.toString());
}
if(c==j4){
System.exit(0);
}
}// end of actionPerformed
}
public static void main(String[] args) {
GUI j=new GUI();
j.setVisible(true);
}
}
The problem occurs in the button 1 and 2
if(c==j1) {
t1.setText( "Your Balance is: "+a.toString());
}
if(c==j2){
a.set_add_Balance(50.0);
t1.setText( "Your Balance is: "+a.toString());
}
I tried to fix it, but I don't know the cause of the program
I added commend to the account class to make it easier to understand.
Please lead me to the solution.
Thank you very much in advance.
Upvotes: 1
Views: 165
Reputation: 13177
Your variable a
is declared, but never initialized. It therefore has value null
. If you then call a.toString()
, like you do when setting the text, you get a NullPointerException
.
You should change the declaration to something like:
Account a = new Account(50.0);
Upvotes: 2