我一直在尝试学习和摆弄代码。我遇到了一些我没想到会发生的事情。我在 MainApp 类中有一个 JLabel,我创建了一个传递 JLabel 的 ActionListener (HelloListener)。按下按钮时,actionPerformed 方法应将 JLabel 更新为“Hello Again!”。确实如此,但为什么会这样让我感到困惑。
但是,我想我必须返回新的 JLabel?当我将HelloListener传递给JLabel时,传递后JLabel不就是HelloListener类的属性吗?那么当它更新时,它只会更新 HelloListener 中的那个,然后我就必须返回它?
为什么当我更新 HelloListener 中的 JLabel 时,它也会在 MainApp 类中更新?
代码如下:
public class MainApp extends JFrame {
public static void main(String[] args) {
new MainApp();
}
public MainApp() {
setLayout(new GridLayout (2,1));
setSize(200,200);
JLabel jl = new JLabel("Hello!");
add(jl);
JButton jb = new JButton("Click me!");
jb.addActionListener(new HelloListener(jl));
add(jb);
setVisible(true);
}
}
和
public class HelloListener implements ActionListener {
JLabel jl;
public HelloListener(JLabel jl) {
this.jl = jl;
}
@Override
public void actionPerformed(ActionEvent arg0) {
jl.setText("Hello again!");
}
}
最佳答案
When I pass the HelloListener the JLabel, isn't that JLabel the property of the HelloListener class after it is passed? So when it updates it will only update the one in HelloListener, and I would then have to return it?
这就是你的理解崩溃的地方。当您“传递 JLabel”时,您正在传递对 JLabel 的引用(您实际上是按值传递引用,您应该在了解当前问题后立即查找该引用,因为它是对于 Java 来说非常重要)。底层对象实例仍然存在于之前存在的任何地方。因此,HelloListener
实例中的 JLabel jl
只是对 gui 中显示的同一实际 JLabel 实例的引用。
这是 Java(以及许多编程语言)工作原理的基础。如果你这样做
Dog d = new Dog();
然后将d
传递给方法
步行(d);
和步行
看起来像
public void walk(Dog dog) {
dog.setLastWalkTime(now());
dog.attachLeash();
}
方法中的 dog
和调用范围中的 d
,都指向同一个 Dog 实例。因此,当您设置lastWalkTime时,底层实例就会被修改。如果在 walk
之后您查看 d
,您将看到您在该方法中设置的 lastWalkTime
值。
关于Java - ActionListener 类变量一致性.. 为什么这有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10088775/