I’ve just been trying to learn and messing around with code. And I’ve come across something I did not expect to happen. I have a JLabel in a MainApp class, I create an ActionListener (HelloListener) which is passed the JLabel. When the button is pressed, the actionPerformed method should update the JLabel to “Hello again!”. And it does, but why it does it confuses me.
However, I thought I would have to return the new JLabel? 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?
Why when I update the JLabel in the HelloListener does it also update in the MainApp class?
Here’s the code:
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);
}
}
and
public class HelloListener implements ActionListener {
JLabel jl;
public HelloListener(JLabel jl) {
this.jl = jl;
}
@Override
public void actionPerformed(ActionEvent arg0) {
jl.setText("Hello again!");
}
}
This is where the breakdown in your understanding is. When you “pass the JLabel”, you are passing a reference to the JLabel (you are actually passing the reference by value, which you should look up as soon as you understand your current issue, because it is very important with Java). The underlying object instance still exists everywhere it did before. So the
JLabel jlin theHelloListenerinstance is just a reference to the same actual JLabel instance that is presented in the gui.This is fundamental to how Java (and many programming languages) works. If you do
Dog d = new Dog();and then pass
dto a methodwalk(d);and
walklooks likedogin the method, anddin the calling scope, both point to the same Dog instance. So as sson as you set the lastWalkTime, the underlying instance is modified. If right afterwalkyou looked atd, you would see thelastWalkTimevalue you set in the method.