2

好吧,第一次问问题通常我可以通过快速搜索找到这些类型的答案,这让我太沮丧了。这是一个简单的小程序,需要工作时间和工资率才能获得总工资和净工资,其中大部分只是我的试运行(净工资等的金额),但在我走得更远之前,我想让它工作。

按下按钮时没有任何反应,不完全确定原因。(最近,当我尝试这个和那个时,我开始在 IE 中得到一个 NullPointerException,可能与我的问题无关,但也只是把它扔在那里。)感谢任何帮助,我尝试了一些事情,但我肯定java生锈了!

继承人的代码:

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

public class ButtonGrossPay extends JApplet implements ActionListener
{

 private JTextField txtHourWork;
 private JTextField txtHourRate;
 private JLabel lblGrossPay;
 private JLabel lblNetPay;

  public void init () {
    Container content_pane = getContentPane ();
    content_pane.setLayout (new FlowLayout ());     

        JLabel lblHourWork = new JLabel("Hours Worked");
        JTextField txtHourWork = new JTextField(10);
        JLabel lblHourRate = new JLabel("Pay Rate");
        JTextField txtHourRate = new JTextField(10);


        JButton btnCalculate = new JButton("Calculate Pay");
        btnCalculate.addActionListener(this);

        content_pane.add (lblHourWork);
        content_pane.add(txtHourWork);
        content_pane.add(lblHourRate);
        content_pane.add(txtHourRate);
        content_pane.add(btnCalculate);
        content_pane.add(lblGrossPay);
        content_pane.add(lblNetPay);
        }

 public void actionPerformed (ActionEvent event) {

        String firstNumber = txtHourWork.getText();
        String secondNumber = txtHourRate.getText();

        int number1 = Integer.parseInt(firstNumber);
        int number2 = Integer.parseInt(secondNumber);

        int gross = number1 * number2; 


        double netPay = 0;
        if (gross >= 0 && gross <= 99.99) {
        netPay = gross - gross * .10;
    } else if (gross >= 99.99) {
        netPay = gross - gross * .20;
    }

    lblGrossPay.setText(Integer.toString(gross));
    lblNetPay.setText(Double.toString(netPay));

    }
}
4

2 回答 2

3

你正在隐藏你的变量——在类的init()方法中重新声明它们,这样所有的类 JTextFields 都不会被初始化,因此是空的。解决方案:不要这样做。

所以把它改成这样:

public void init () {
    Container content_pane = getContentPane ();
    content_pane.setLayout (new FlowLayout ());     

    JLabel lblHourWork = new JLabel("Hours Worked");
    // JTextField txtHourWork = new JTextField(10);
    JLabel lblHourRate = new JLabel("Pay Rate");
    // JTextField txtHourRate = new JTextField(10);

    txtHourWork = new JTextField(10);
    txtHourRate = new JTextField(10);
于 2012-11-06T02:09:32.530 回答
0

您永远不会初始化JLabels lblGrossPaylblNetPay导致NPE. 你应该有:

 lblGrossPay = new JLabel();
 lblNetPay = new JLabel();
于 2012-11-06T02:10:48.170 回答