gpt4 book ai didi

java - 关于方法中声明的内部类中变量的可见性的一些疑问

转载 作者:行者123 更新时间:2023-12-02 06:32:43 26 4
gpt4 key购买 nike

我对该方法的工作原理有以下疑问:

protected JButton createToolbarButton(String name, final String id, final JPanel panel)
{
JButton button = new JButton(name); // Create a new JButton

// If the passed Jpanel named "panel" exist, add this to the JPanel named content (the CardLayout container)
if (panel != null)
content.add(panel, id);
else
button.setEnabled(false); // Otherwise disable this button

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
//System.out.println(panel.getClass());
if (panel instanceof SchedulingPanel)
((SchedulingPanel)panel).getTasksSettings().fireSettingsUpdated();
else if (panel instanceof EventsPanel)
((EventsPanel)panel).refreshPanel();
else if (panel instanceof ConfigurationPanel)
((ConfigurationPanel)panel).refreshPane();

showSection(id);
}
});

return button;
}

我有一个名为CreateToolbarButton的方法,它有一些输入参数,包括String id参数。

正如您在此方法中看到的,我向 JButton 对象添加了一个 ActionListener 内部类(用于处理此按钮上的单击事件)。

在这个 ActionListener 内部类中,声明了处理点击事件的 actionPerformed() 方法,并在此方法的末尾调用 showSection( id) 方法将 id 参数传递给 id,该参数似乎与 createToolbarButton() 输入参数相同。

所以在我看来,在我的 ActionListener 内部类中,我还可以看到容器方法的参数和变量 (createToolbarButton())

是吗?为什么?我觉得有点奇怪

Tnx

安德里亚

最佳答案

是的,你确实有知名度。这些变量是最终变量这一事实保证了这一点。换句话说,由于它们不会更改,因此内部类不会尝试引用在 createToolbarButton 方法完成时可能消失的变量。

如果您认为这种行为很奇怪并且您不希望出现这种情况,请不要使用内部类。请改用通用的第一级类。

关于java - 关于方法中声明的内部类中变量的可见性的一些疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19936092/

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