我正在尝试为我正在学习的 Java 类创建一个 GUI 工资计算器。要求是它必须接受用户输入(使用 JComboBox),计算每周工资并将结果添加到 JTable。用户应该能够继续为其他员工计算并有一个退出按钮。我在主类中创建了 GUI,需要两个 ActionListener,一个用于退出,一个用于计算并添加到 JTable。
我的问题是,当我开始计算 ActionListener 时,它无法识别我在主类中设置的变量。我已经尝试将它们公开,使用主类名 DOT 变量名(PayrollCalc.empName),初始化它们,但似乎没有任何效果。代码不完整,因为在我可以先完成实际计算之前,我什至还没有开始添加到 JTable。有没有人有什么建议?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PayrollCalc {
public static void main(String[] args) {
//Declare variables used
String empName = null, entDept = null, calcdPay = null;
String[] empDept = {"Marketing","IT","Accounting","Development","Payroll","Facilities"};
String columnNames[] = {"Name","Department","Pay Check"};
String dataValues [][] = {
{empName,entDept,calcdPay}
};
double wrkHours = 0;
double empRate = 0;
double wklyPay = 0;
//Create JTable and scrollPane for output
JTable table;
JScrollPane scrollPane;
table = new JTable (dataValues,columnNames);
scrollPane = new JScrollPane(table);
//Create JFrame object with title
JFrame frame = new JFrame("Employee Payroll Calculator");
//Create combo box for department choices
JComboBox combo = new JComboBox(empDept);
JTextField nameField = new JTextField(15);
JTextField hourField = new JTextField(10);
JTextField rateField = new JTextField(10);
//Create JLables for input fields
JLabel nameLbl = new JLabel ("Name:");
JLabel hourLbl = new JLabel ("Hours:");
JLabel rateLbl = new JLabel ("Rate:");
JLabel deptLbl = new JLabel ("Department:");
//Create buttons for ActionListners
JButton exitButton= new JButton("Exit");
exitButton.addActionListener(new exitApp());
exitButton.setSize(5,5);
JButton calcButton= new JButton("Calculate");
calcButton.addActionListener(new calcApp());
calcButton.setSize(5,5);
//Create panels
Panel panel1 = new Panel();
panel1.add(nameLbl);
panel1.add(nameField);
panel1.add(deptLbl);
panel1.add(combo);
panel1.add(hourLbl);
panel1.add(hourField);
panel1.add(rateLbl);
panel1.add(rateField);
panel1.add(rateField);
Panel panel2 = new Panel();
panel2.add(calcButton);
Panel panel3 = new Panel();
panel3.add(calcButton);
panel3.add(exitButton);
Panel panel4 = new Panel();
panel4.add(scrollPane, BorderLayout.CENTER);
//creates the frame
frame.setSize(950,200);
frame.add(panel1,BorderLayout.NORTH);
frame.add(panel2);
frame.add(panel3, BorderLayout.SOUTH);
frame.add(panel4);
frame.setVisible(true);
}
//ActionListner for Exit button
static class exitApp implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
//ActionListner for Calculate button
static class calcApp implements ActionListener
{
public void actionPerformed(ActionEvent c)
{
empName = nameField.getText();
entDept = combo.getName();
wrkHours = Double.parseDouble(hourField.getText());
empRate = Double.parseDouble(rateField.getText());
wklyPay = wrkHours * empRate;
calcdPay = new Double(wklyPay).toString();
}
}
}