为什么我的价值观没有转移过来

时间:2014-12-01 20:30:31

标签: java

在我的程序中输入一个值后,为什么我的值不会传递?我知道我错过了一些简单的东西,但我不能把手指放在上面。

任何帮助都将不胜感激。

我遇到问题的部分是“actionPerformed”方法。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PayBillGUI extends JFrame implements ActionListener{

double totalDue = 0.0;
double taxRate = 0.0;
double tipRate = 0.0;
double totalOwed = 0.0;


private JButton calcBtn;
private JButton exitBtn;
private JLabel totalLbl;
private JTextField totalTxt;
private JLabel taxLbl;
private JTextField taxTxt;
private JLabel tipLbl;
private JTextField tipTxt;
private JLabel owedLbl;
private JLabel numOweLbl;

private  Container container;


public PayBillGUI(String title)
{
    super(title);
    setSize(225, 200);
    initializeUserInterface();
}

public void initializeUserInterface() 
{

    container = this.getContentPane();
    container.setLayout(new GridLayout(0,2));


    calcBtn = new JButton("Calculate");
    exitBtn = new JButton("Exit");
    totalLbl = new JLabel("Total Due: ");
    totalTxt = new JTextField(5);
    taxLbl = new JLabel("Tax Rate: ");
    taxTxt = new JTextField(5);
    tipLbl = new JLabel("Tip Rate: ");
    tipTxt = new JTextField(5);
    owedLbl = new JLabel("Total owed:");
    numOweLbl = new JLabel("$" + totalOwed);


    container.add(totalLbl);
    container.add(totalTxt);

    container.add(taxLbl);
    container.add(taxTxt);

    container.add(tipLbl);
    container.add(tipTxt);

    container.add(owedLbl);
    container.add(numOweLbl);

    container.add(calcBtn);
    container.add(exitBtn);

    calcBtn.addActionListener(this);
    exitBtn.addActionListener(this);
}

public void actionPerformed(ActionEvent event){

    String buttonText = calcBtn.getText();
    if (event.getActionCommand().equals(buttonText))
    {
        container.remove(numOweLbl);

        totalDue = Double.parseDouble(totalTxt.getText());
        taxRate = (Double.parseDouble(taxTxt.getText()) / 100) * totalDue;
        tipRate = (Double.parseDouble(tipTxt.getText()) / 100) * totalDue;

        totalOwed = totalDue + taxRate + tipRate;
        container.add(numOweLbl);
        validate();

    }
    else
    {
        System.exit(0);
        validate();
    }
}

}

1 个答案:

答案 0 :(得分:0)

actionPerformed的您的其他屏蔽栏中,您在到达validate()之前退出。

问题可能如下:

您正在向您的用户界面添加numOweLbl,但您从未将其文本设置为totalOwed

在执行container.add(numOweLbl)之前,您需要设置其文本。

numOweLbl.setText(totalOwed)