gpt4 book ai didi

java ;如何获取 Action 监听器之外的变量?

转载 作者:行者123 更新时间:2023-12-01 17:55:16 24 4
gpt4 key购买 nike

注意:我的英语不是最好的,所以请不要介意太多语法错误。

嘿,这里是java初学者,无论如何,我正在编写我的CPS测试程序,就像第一个小程序一样。无论如何,这个问题之前可能已经被问过,但是,我需要在 ActionListener 代码之外获取一个变量:

public static void startB() {
Font f = new Font(null, Font.BOLD , 0);

Font size = f.deriveFont(20f);

JLabel text = new JLabel("");
text.setPreferredSize(new Dimension(250,250));
text.setFont(size);

JButton b = new JButton();
JFrame cps = new JFrame("CLICK");
cps.setPreferredSize(new Dimension(400,400));
cps.setLocationRelativeTo(null);
cps.setLayout(new FlowLayout());
b.setText("<html> CLICK ME <br> As much as you can! <html> ");
cps.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cps.getContentPane().add(b , BorderLayout.CENTER);
cps.getContentPane().add(text, BorderLayout.CENTER);
cps.pack();
cps.setVisible(true);

text.setText("<html> Starting in... <br> 3<html>");
try {
TimeUnit.SECONDS.sleep((long)1.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.setText("<html> Starting in... <br> 2<html>");
try {
TimeUnit.SECONDS.sleep((long)1.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.setText("<html> Starting in... <br> 1<html>");
try {
TimeUnit.SECONDS.sleep((long)1.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.setText("<html> CLICK! <html>");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double clicks = 0;
clicks++;
// How to get Clicks variable out of the actionListener?
}
});
try {
TimeUnit.SECONDS.sleep((long)10.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//I need get the Clicks Variable to here.
}

如果您能帮助我,请回复该帖子。谢谢。

最佳答案

这里创建一个 ActionListener 的匿名类:

b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double clicks = 0;
clicks++;
// How to get Clicks variable out of the actionListener?

}
});

并且您在其中声明了 clicks 变量。
您可以在外部类中声明 clicks,但它不会起作用,因为编译器期望 clicksfinal。这与您对它的使用不兼容:您在 actionPerformed() 中对其进行了变异。

满足您的需求的另一种方法是创建 ActionListener 的非匿名实现,您将在其中将 clicks 存储为字段并提供 getter 来检索其值。

它可能是一个内部类:

private static class MyActionListener implements ActionListener {

private double clicks;

@Override
public void actionPerformed(ActionEvent e) {
clicks++;
}

public double getClicks() {
return clicks;
}

}

你可以这样使用它:

MyActionListener actionListener = new MyActionListener();
myComponent.addActionListener(actionListener);
...
// later retrieve clicks
double clicks = actionListener.getClicks();

关于 java ;如何获取 Action 监听器之外的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45544048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com