【问题标题】:ActionListener not recognizing variables from main classActionListener 无法识别主类中的变量
【发布时间】:2013-07-05 16:09:46
【问题描述】:

我正在尝试为我正在学习的 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();
        }

    }

}

【问题讨论】:

  • 您尚未在主中设置变量。您在主方法中有局部变量。
  • 将这些变量添加到该方法之外并设置访问级别(私有、公共等)。

标签: java swing variables inheritance actionlistener


【解决方案1】:

看,每个变量都有它的作用域……你还没有定义任何东西作为成员类变量,所以没有任何东西可以作为全局变量。

you have defined variable inside main method () so their scope is limited to only main method这就是你问题背后的原因。

【讨论】:

  • 谢谢 Tushar,我知道这很简单。
  • 接受它作为你的答案!
【解决方案2】:

由于您尝试在 ActionListener 中访问的变量对于您的 main() 来说是本地,因此它们对它们不可见你的 static 类。此外,在 static main() 中初始化您的 GUI 会强制在每个地方使用 statics,正如您从下面的 cmets 中可以看出的那样,这是一种不好的做法。

因此,将初始化移到 构造函数 并将局部变量作为 instance 级别的成员字段。除此之外,您还需要从 静态嵌套 类切换到使用 inner 类。

Instance 类的成员随后将可供您的 inner ActionListener 类使用。

public class PayrollCalc {

    //Declare variables used
    private String empName = null, entDept = null, calcdPay = null;

    private double wrkHours = 0;
    private double empRate = 0;
    private double wklyPay = 0;

    private JComboBox combo;
    private JTextField nameField;
    private JTextField hourField;
    private JTextField rateField;

    public static void main(String[] args) {
        new PayrollCalc();
    }

    public PayrollCalc() {
        // ...
        combo = new JComboBox(empDept);
        nameField = new JTextField(15);
        hourField = new JTextField(10);
        rateField = new JTextField(10);
        // ...
    }

    // non-static ActionListener inner classes
}

【讨论】:

  • “将它们作为类级静态成员字段移出。” static 部分是一个糟糕的举措和糟糕的建议。
  • @AndrewThompson OP 正在初始化静态 main 中的所有内容,并且侦听器也是静态的。因此,我建议快速修复。再次研究答案。请过五点再来查看。
  • @AndrewThompson:请注意再看看我的回答。谢谢。
  • @MonadNewb:请再看看我的回答。谢谢。
  • @RaviThapliyal Care 赞成投票。 :) (
猜你喜欢
  • 2015-05-09
  • 2012-01-10
  • 2021-01-06
  • 2021-02-27
  • 2013-05-15
  • 2018-11-12
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
相关资源
最近更新 更多