Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JAVA如何在操作侦听器外部获取变量?_Java - Fatal编程技术网

JAVA如何在操作侦听器外部获取变量?

JAVA如何在操作侦听器外部获取变量?,java,Java,注意:我的英语不是最好的,所以请不要介意有太多语法错误 嘿,这里是java初学者,不管怎样,我正在编写我的CPS测试程序,就像第一个迷你程序一样。不管怎样,这个问题以前可能被问过,但是, 我需要获取ActionListener代码之外的变量: public static void startB() { Font f = new Font(null, Font.BOLD , 0); Font size = f.deriveFont(20f); JLabel text = ne

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

嘿,这里是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.
}
publicstaticvoidstartb(){
Font f=新字体(空,Font.BOLD,0);
Font size=f.deriveFont(20f);
JLabel text=新的JLabel(“”);
text.setPreferredSize(新尺寸(250250));
text.setFont(大小);
JButton b=新JButton();
JFrame cps=新JFrame(“单击”);
cps.setPreferredSize(新尺寸(400400));
cps.setLocationRelativeTo(空);
setLayout(新的FlowLayout());
b、 setText(“尽可能多地单击我”
); cps.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); cps.getContentPane().add(b,BorderLayout.CENTER); cps.getContentPane().add(文本,BorderLayout.CENTER); cps.pack(); cps.setVisible(真); setText(“从…
3开始”); 试一试{ 时间单位。秒。睡眠((长)1.0); }捕捉(中断异常e){ //TODO自动生成的捕捉块 e、 printStackTrace(); } text.setText(“开始于…
2”); 试一试{ 时间单位。秒。睡眠((长)1.0); }捕捉(中断异常e){ //TODO自动生成的捕捉块 e、 printStackTrace(); } setText(“从…
1开始”); 试一试{ 时间单位。秒。睡眠((长)1.0); }捕捉(中断异常e){ //TODO自动生成的捕捉块 e、 printStackTrace(); } text.setText(“单击!”); b、 addActionListener(新ActionListener(){ 已执行的公共无效操作(操作事件e){ 双击=0; 点击++; //如何从actionListener中获取Clicks变量? } }); 试一试{ 时间单位。秒。睡眠((长)10.0); }捕捉(中断异常e){ //TODO自动生成的捕捉块 e、 printStackTrace(); } //我需要把Clicks变量放到这里。 }

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

在这里,您创建了一个名为
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
final
。这与您对它的使用不兼容:您在
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();

在这里,您创建了一个匿名类
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
final
。这与您对它的使用不兼容:您在
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();

您只能在匿名内部类中访问外部类的
final
变量。但正如修饰符
final
所示,一旦赋值,此类变量的值就不能再更改了

为了避免这种情况,您可以使用
AtomicInteger
而不是普通的
int
double
来存储单击并在操作侦听器外部声明此
final
变量:

final AtomicInteger clicks = new AtomicInteger(0);
b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        clicks.incrementAndGet();
    }
}
clicks.get(); // will return the desired number of invocations of actionPerformed
这样,您仍然可以为您的操作侦听器使用匿名类


不过,从代码样式的角度来看,最好定义一个命名类,并按照另一个答案中的建议为单击计数提供一个getter。

您只能在匿名内部类中访问外部类的
final
变量。但正如修饰符
final
所示,一旦赋值,此类变量的值就不能再更改了

为了避免这种情况,您可以使用
AtomicInteger
而不是普通的
int
double
来存储单击并在操作侦听器外部声明此
final
变量:

final AtomicInteger clicks = new AtomicInteger(0);
b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        clicks.incrementAndGet();
    }
}
clicks.get(); // will return the desired number of invocations of actionPerformed
这样,您仍然可以为您的操作侦听器使用匿名类


不过,从代码风格的角度来看,最好按照另一个答案中的建议定义一个命名类,并为单击计数提供一个getter。

@davidxxx我刚才提供了一个问题的答案,并且已经提到,这不是最好的方法。啊,对不起,我读得不好。我的理解恰恰相反。这是一个很好的替代警告。@davidxxx我刚才提供了一个问题的答案,并且已经提到,这不是最好的方法。啊,对不起,我读错了。我的理解恰恰相反。这是一个很好的替代警告。