首先,在初始化菜單項的類中,需要聲明一個整數數組。這些將被初始化爲0自動:
private int[] counters = new int[16];
以後每次初始化一個菜單項時,必須將偵聽器添加到增加相應的計數器元素的項目:
private class CounterIncrementActionListener implements ActionListener {
private int index;
private CounterIncrementActionListener(int index) {
this.index = index;
}
@Override
public void actionPerformed(ActionEvent e) {
counters[index] = counters[index] + 1;
}
}
...
firstItem.addActionListener(new CounterIncrementActionListener(0));
secondItem.addActionListener(new CounterIncrementActionListener(1));
...
現在,當幀關閉時,能夠將計數器陣列保存到文件中,您需要向幀添加窗口監聽器:
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
saveCounters();
System.exit(0);
}
}