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!");
}
}