Reputation: 23
I am not running into any errors but nothing happens when I run the program. Any help would be appreciated. I just need to be able to add a starting balance and then calculate a deposit or withdraw.
package account;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class GUI implements ActionListener{
JTextField txt, txt2, txt3;
JButton submit;
JLabel balance;
double Balance = 0.00;
GUI(){
JFrame main = new JFrame("Account GUI ");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt = new JTextField(10);
txt2 = new JTextField(10);
txt3 = new JTextField(10);
JPanel gui = new JPanel(new BorderLayout(8,8));
gui.setBorder(new EmptyBorder(8,8,8,8));
main.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Starting Balance"));
controls.add(txt);
txt.addActionListener(this);
labels.add(new JLabel("Deposit Amount: "));
controls.add(txt2);
txt2.addActionListener(this);
labels.add(new JLabel("Withdraw Amount: "));
controls.add(txt3);
txt3.addActionListener(this);
submit = new JButton("Submit");
gui.add(submit, BorderLayout.SOUTH);
balance = new JLabel("New Balance " + Balance);
gui.add(balance,BorderLayout.NORTH);
submit.addActionListener(this);
main.pack();
main.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
if (txt!=null){
double strtblnc = Double.parseDouble(txt.getText());
Balance = Balance + strtblnc;
}
else if (txt2!=null){
double dpst = Double.parseDouble(txt2.getText());
Balance = Balance + dpst;
}
else if(txt3!=null){
double wthdrw = Double.parseDouble(txt3.getText());
Balance = Balance - wthdrw;
}
}
public static void main(String[] args) {
GUI test = new GUI();
}
}
Upvotes: 2
Views: 143
Reputation:
The reason why you are not receiving a new balance number is because you are never actually resetting the text to your JLabel. When you originally initialized:
balance = new JLabel("New Balance " + Balance);
You set Balance to 0.00. With that being said, you will need to add:
balance.setText("New Balance " + Balance);
to give you the updated Balance.
I also noticed that the code you posted did not work if you left a text field blank. Look at the updated code below and try this.
public void actionPerformed(ActionEvent arg0) {
double strtblnc;
double dpst;
double wthdrw;
String sTxt = txt.getText();
String sTxt2 = txt2.getText();
String sTxt3 = txt3.getText();
if(sTxt.isEmpty())
sTxt = "0";
if(sTxt2.isEmpty())
sTxt2 = "0";
if(sTxt3.isEmpty())
sTxt3 = "0";
dpst = Double.parseDouble(sTxt2);//parses deposit;
strtblnc = Double.parseDouble(sTxt); //parses starting balance;
wthdrw = Double.parseDouble(sTxt3); //parses withdraw;
Balance = Balance + strtblnc + dpst - wthdrw;
balance.setText("New Balance " + Balance);
}
Upvotes: 1