我没有遇到任何错误,但是当我运行程序时没有任何反应。任何帮助,将不胜感激。我只需要能够添加起始余额然后计算存款或取款。
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();
}
}
答案 0 :(得分:1)
您没有收到新余额的原因是因为您实际上从未将文本重置为JLabel。最初初始化时:
balance = new JLabel("New Balance " + Balance);
您将Balance设置为0.00。话虽如此,您还需要添加:
balance.setText("New Balance " + Balance);
为您提供更新的余额。
我还注意到,如果您将文本字段留空,则您发布的代码无效。请查看下面的更新代码并尝试此操作。
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);
}