我有一个计数器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++;
}
});
答案 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
接口,并通过依赖注入提供实现,这样您就可以适当地伪造时间