JButton 不会计算输入值 (Java)

JButton Won't Calculate Inputted Value (Java)

所以我正在为我的 class 做作业,现在我被卡住了。我想计算输入的值,但每次我按下按钮它都不会做任何事情。讲师确实提出了我遵循的说明,但我遗漏了一些东西。所以请尽量不要更改代码,我将 post 代码后我坚持的说明。

package assignment.pkg16;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
public class Assignment16  extends JFrame implements ActionListener
{
  Container content = this.getContentPane();

  JTextField tfAmountBorrowed = new JTextField (15);
  JTextField tfIR= new JTextField (15);
  JTextField tfYearsToPay= new JTextField (15);

  JLabel lblPayment = new JLabel("Monthly Payment");
  JLabel lblTotCost = new JLabel("Total Cost");

  JButton btnCalculate = new JButton("Calculate");
   public  Assignment16()
      {
        this.createWindow();
        JLabel aBorrowed = new JLabel("Amount Borrowed");
        content.add(aBorrowed , BorderLayout.EAST);
        add(tfAmountBorrowed);
        JLabel intrestRate= new JLabel("Interest Rate (EX. 7.5)");
        content.add(intrestRate , BorderLayout.EAST);
        add(tfIR);
        JLabel yTp = new JLabel("Years To Pay");
        content.add(yTp , BorderLayout.EAST);
        add(tfYearsToPay);
        content.add(btnCalculate, BorderLayout.SOUTH);
        btnCalculate.addActionListener(this);
      }

    public void createWindow()
      {
          content.setLayout(new GridLayout(0, 2, 5, 5));
         this.setVisible(true);
         this.setTitle("First GUI App");
         this.setSize(350, 300);
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }



    @Override
     public void actionPerformed(ActionEvent ae) 
       {  
         String amountStr = tfAmountBorrowed.getText();
         String intrestRateStr = tfIR.getText();
         String yearsToPayStr = tfYearsToPay.getText();

         Double amountDbl = new Double(amountStr);
         Double intrestRateDbl = new Double(intrestRateStr);
         Double yearsToPayDbl = new Double(yearsToPayStr);

         double amount = amountDbl.doubleValue();
         double intrestRate = intrestRateDbl.doubleValue();
         double yearsToPay = yearsToPayDbl.doubleValue();

         double intrestFormula = ( ( intrestRate/100 ) /12 );
         double payment = ( 1 - ( Math.pow( 1 / (1+intrestRate) , yearsToPay * 12 ) ) );

         NumberFormat fmt = NumberFormat.getCurrencyInstance();
         lblPayment.setText("" + fmt.format(intrestFormula));
         lblTotCost.setText( ""+ fmt.format(payment ) );
        }


public static void main(String[] args) {
    Assignment16 a16 = new Assignment16();

}



}

Convert the input. The input entered by the user is in textual form. Before you can do calculations however, you need to convert it to binary form. Because the HowMuch application deals with fractional numbers you should convert each entry to a double value.

Here are the steps required to convert a String like "123.45" into a floating point double value. For more in-depth information, make sure you read Learning Unit 8B, "Data-In & Data Out".

  • Create a local Double object for each of the String variables extracted in Step 5. Construct your Doubleobjects by passing each String to the appropriate constructor, like this:
       Double amountDbl = new Double(amountStr);

where amountStr is one of the String variables initialized in Step 5. [Note that a Double variable is different than a double [little d] variable. A Double variable is an object, but it can't be used for arithmetic. A doublevariable is a primitive value.]

  • Create a primitive double local variable to match each of the Double objects created in the previous step. Initialize your double variables by sending your Double objects the doubleValue() message, like this:
    double amount = amountDbl.doubleValue();

Step 8

Perform the calculations. Now that you've retreived the information from the user you'll need to manipulate that information to calculate the answers required by the problem.

Here's what you need to know to perform your calculations:

The formula to calculate a payment when the loan amount, interest rate, and term are all known is:

                  loan amount x interest rate 
    payment = ____________________________________

              1 - (1 / (1 + interest rate))term * 12

When you perform your calculations you can use two of the numbers you obtained in the previous step--loan amount and loan term--without any further processing.

You need to modify the interest rate variable, however, before you can use it because the user expects a monthly rate and the user entered a yearly rate. In addition, the rate entered by the user needs to be converted to a decimal percentage.

Here's what you need to do:

  • Since the user entered the interest rate as 7.5, rather than .075, the first step is to divide the interest rate by 100 and store the result back in the interest rate variable. This is the actual yearly interest rate.
  • The formula above however, requires a monthly interest rate not a yearly one. Divide the interest rate calculated in the previous step, this time by 12, and store the result back in your interest rate variable.

Once the interest rate is squared away create a new double variable called payment and plug the rest of the variables into the formula shown above storing the result in payment. Since Java doesn't have an exponentiation operator you'll have to use the Math.pow() method to calculate the "bottom" part of the interest calculation like this:

(1 - (Math.pow(1/(1+rate), term * 12)))

Step 9

Display the output. To display the output send the setText() message to the JLabel objects you created in Step 3. One complication is that you have to convert your new binary answers back into Strings before they can be displayed.

Here's a summary of how to do that.

  • Create a new local NumberFormat object using the getCurrencyInstance() method.
  • Send your NumberFormat object the format() message. Pass the number you want formatted as an argument.
  • Save the formatted String obtained by calling the format() method, and pass it to the appropriate setText()method.

variable [computed in Step 8] for the first output label. For the total cost label, simply multiply the monthly payment by 12 and then multiply the result by the term to find the total cost. paymentFormat the

我已经正确完成了所有其他步骤,但是该程序无法运行。所以请帮助并谢谢你。 =)

另外弹出一个错误:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at java.lang.Double.<init>(Double.java:608)
at assignment.pkg16.Assignment16.actionPerformed(Assignment16.java:59)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access0(EventQueue.java:97)
at java.awt.EventQueue.run(EventQueue.java:709)
at java.awt.EventQueue.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue.run(EventQueue.java:731)
at java.awt.EventQueue.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

天哪!您永远不会将 lblPayment 和 lblTotCost JLabel 添加到您的 GUI 中。您可以将他们的文本设置为您想要的任何内容,但在您解决此问题之前不会显示任何内容。

根据我的发现,您忘记将 lblPayment 和 lblTotCost 添加到您的内容中。

找到这段代码 "add(tfYearsToPay);" 然后添加 add(lblPayment); & 添加(lblTotCost);就在 "add(tfYearsToPay);" 下面,就在您将按钮添加到内容之前。

add(tfYearsToPay);
add(lblPayment);
add(lblTotCost);
content.add(btnCalculate, BorderLayout.SOUTH);
btnCalculate.addActionListener(this);

按 control + shift + f(应该格式化,但您的键可能不同)

使用 add 方法在 GUI 中添加您需要的任何内容。还要添加动作侦听器并告诉该按钮进行您想要的计算,在这种情况下是您期望它执行的动作。例如myButton.addActionListener(handleAction) 听众class 必须知道这是什么所以你也必须告诉它。那就是注册。在您的构造函数中将组件添加到 GUI,确保您使用适当的布局管理器。这些可能并不总是由您的老师作为说明的一部分给出。