在两个ActionListeners中调用的计数器

时间:2013-12-04 06:42:51

标签: java swing actionlistener counter

我有一个计数器x,我想在两个单独的ActionListener中调用它。当我尝试将x变为final时,我无法使用x++;增加。我试图在嵌套中创建x,但是我不能在另一个ActionListener中使用相同的值。代码如下:

buttonIn.addActionListener(new ActionListener() {
    String reportDate = "";
    int x = 0;
        public void actionPerformed(ActionEvent e)
        {

            DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
            Date time = new GregorianCalendar().getTime();
            reportDate = df.format(time);
            String confirm = name.getText() + " has checked in at " + reportDate;
            timeLabel.setText(confirm);
            timeLabel.setVisible(true);
            String action = "Time In";

            reportData[x][0] = name.getText();
            reportData[x][1] = "Time In";
            reportData[x][2] = reportDate;
            x++;
            System.out.println(x);
        }
});
buttonOut.addActionListener(new ActionListener() {
    String reportDate = "";
        public void actionPerformed(ActionEvent e)
        {
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
            Date time = new GregorianCalendar().getTime();
            reportDate = df.format(time);
            String confirm = name.getText() + " has checked out at " + reportDate;
            timeLabel.setText(confirm);
            timeLabel.setVisible(true);
            reportData[x][0] = name.getText();
            reportData[x][1] = "Time Out";
            reportData[x][2] = reportDate;
            x++;
        }
});   

1 个答案:

答案 0 :(得分:1)

一个简单的选择是使用AtomicInteger代替 - 然后变量可以是最终的,但您仍然可以增加包装的值。所以:

final AtomicInteger counter = new AtomicInteger(0);
buttonIn.addActionListener(new ActionListener() {
    // Within here, you can use counter.get and counter.incrementAndGet
});
buttonOut.addActionListener(new ActionListener() {
    // Within here, you can use counter.get and counter.incrementAndGet
});

我也强烈考虑将该代码提取到一个单独的类中 - 几乎所有代码都是相同的,因此您应该能够通过参数化差异来删除重复。所以你最终会得到类似的东西:

AtomicInteger counter = new AtomicInteger(0);
buttonIn.addActionListener(new ReportListener(
    counter, reportData, "%s has checked in at %s", "Time In"));
buttonOut.addActionListener(new ReportListener(
    counter, reportData, "%s has checked out at %s", "Time Out"));

(其中ReportListener是实施ActionListener的新类。)

此外:

  • 强烈怀疑您想在HH
  • 中使用hh而不是SimpleDateFormat
  • 考虑要在SimpleDateFormat中使用哪个时区和区域设置,并明确指定它们
  • 要获取当前时间,只需致电new Date()而不是创建日历并从中提取日期
  • 没有明显的理由将reportDate作为实例变量
  • 为了测试性,我建议您使用某种Clock接口,并通过依赖注入提供实现,这样您就可以适当地伪造时间
  • 考虑使用Joda Time进行所有日期/时间工作;它比内置的日期/时间API更清洁