gpt4 book ai didi

java - Action 事件最终变量?

转载 作者:行者123 更新时间:2023-11-29 06:39:12 25 4
gpt4 key购买 nike

我有以下代码,但在第 19 行出现错误“无法将值分配给最终变量计数”,但我必须将此变量分配为最终变量才能在“LISTENER”中使用它。哪里错了?

import java.awt.event.*;
import javax.swing.*;


public class ButtonTester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JButton button = new JButton();
frame.add(button);

final int count = 0;

class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
count++;
System.out.println("I was clicked " + count + " times");
}
}

ActionListener listener = new ClickListener();
button.addActionListener(listener);

frame.setSize(100,60);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

最佳答案

final 变量一旦赋值就不能修改。解决方案是使该变量成为您的 ClickListener 类的成员:

import java.awt.event.*;
import javax.swing.*;


public class ButtonTester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JButton button = new JButton();
frame.add(button);

class ClickListener implements ActionListener
{
int count = 0;
public void actionPerformed(ActionEvent event)
{
count++;
System.out.println("I was clicked " + count + " times");
}
}

ActionListener listener = new ClickListener();
button.addActionListener(listener);

frame.setSize(100,60);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

关于java - Action 事件最终变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14814854/

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