我的程序中有一个JButton,定义如下(或多或少)
public class MyTester{
public static void main(String[] args)
{
int counter = 0;
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.doSomething()
counter++;
}
}
);
}
}
我希望能够计算单击按钮的次数。问题是,我无法声明一个计数器然后在调用.doSomething()之后递增它,因为变量必须是最终的,我才能在内部类中引用它。
有没有办法做到这一点,除了用自己的.increment()方法创建自己的包装类?
答案 0 :(得分:2)
根据线程情况,您可以将变量移动到封闭类。但如果你多次调用foo()
,这可能会出错,因为那将使用相同的计数器。
public class MyClass {
// Notice the placement outside the main()
private static int counter = 0;
public static void main(String[] args) {
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.doSomething()
//do some more stuff
counter++;
}
}
);
}
}
答案 1 :(得分:2)
您可以将计数器从ActionListener
外移到内部,使其成为听众的成员。
public class MyTester {
public static void main(String[] args) {
final JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
int counter; // you make one per listener
public void actionPerformed(ActionEvent e) {
startButton.doSomething();
counter++;
}
});
}
}
答案 2 :(得分:1)
正如@akf所建议的那样,计数器可以是嵌套类的成员,从中可以看到封闭实例的成员。此示例实现ActionListener
以扩展AbstractAction
。
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** @see http://stackoverflow.com/questions/4290117 */
public class ClickCount extends JPanel {
private JButton button = new JButton(new ClickHandler("Click"));
private JLabel label = new JLabel("0");
public ClickCount() {
this.add(button);
this.add(label);
}
private class ClickHandler extends AbstractAction {
int counter;
public ClickHandler(String name) {
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(++counter));
}
}
private void display() {
JFrame f = new JFrame("ClickCount");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ClickCount().display();
}
});
}
}