Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding event handling  RSS feed

 
Jacob Collins
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I've got the code from Head First Java to work, and I'm playing around with it. Here is the code from page 371.

One thing I don't understand I've put into the comments below. There is currently a line that says:
button.addActionListener(this);
During experimentation, I replaced it with this line:
button.addActionListener(new SimpleGui3C());
I figured that this should still work, because an instance of the class is still being registered with the listener. And in fact it compiles fine. But when I press the button, nothing happens. Can someone please explain to me in language simple enough for a newbie why this line isn't good enough? Thanks in advance for any help...

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

public class SimpleGui3C implements ActionListener {
JFrame frame = new JFrame();

public static void main(String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}

public void go() {
JButton button = new JButton("Change colors");
button.addActionListener(this);
// Question: WHY doesn't the below line also work?
// button.addActionListener(new SimpleGui3C());
MyDrawPanel drawPanel = new MyDrawPanel();

frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

// general preferences
frame.setSize(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent ae) {
frame.repaint();
}
}
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jacob Collins:
...when I press the button, nothing happens. Can someone please explain to me in language simple enough for a newbie why this line isn't good enough? ...

If you add a println to your actionPerformed method, you will see that clicking on the button does make something happen, so the Listener is working fine.

The difference is in the call to frame.repaint(). If you use "this" as your listener, then the variable "frame" in actionPerformed references the same JFrame instance previously used in the go method, so it's the one that's visible in your GUI. But "frame" is an instance variable, so if you use a new instance of SimpleGui3C as your listener, then "frame" references a different instance of JFrame -- one that has not been used in a go method and is not visible.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!