JPanel.addComponentListener does not work when the listener is a class variable

Posted by Coder on Stack Overflow See other posts from Stack Overflow or by Coder
Published on 2010-05-20T23:08:26Z Indexed on 2010/05/20 23:10 UTC
Read the original article Hit count: 339

I have a public class which has the following method and instance variable:

public void setImagePanel(JPanel value) { imagePanel = value;

  if (imagePanel != null) {

     //method 1 : works
     imagePanel.addComponentListener(new ComponentAdapter() {

        public void componentResized(ComponentEvent evt) {
           System.out.println("Here 1");
        }

     });

     //method 2 :  does not work
     panelResizeListener = new ResizeListener();
     imagePanel.addComponentListener(panelResizeListener);

     //method 3 : works
     //ResizeListener listener = new ResizeListener();
     //imagePanel.addComponentListener(listener);

     //method 4 : works
     //imagePanel.addComponentListener(new ResizeListener());

     //method 5 : does not work -- THIS IS THE DESIRED CODE I WANT TO USE
     imagePanel.addComponentListener(panelResizeListener);
  }

}

public class ResizeListener extends ComponentAdapter {

  @Override
  public void componentResized(ComponentEvent evt) {
     System.out.println("RESIZE 3");
  }

}

private ResizeListener panelResizeListener = new ResizeListener();

Each of the methods above correspond the to code immediately below until the next //method comment. What i don't understand is why i can't use the class instance variable and add that to the JPanel as a component listener.

What happens in the cases above where i say that the method does not work is that i don't get the "RESIZE 3" log messages. In all cases where i list that it works, then i get the "RESIZE 3" messages.

The outer class is public with no other modification except that it implements an interface that i created (which has no methods or variables in common with the methods and variables listed above).

If anyone can help me i would greatly appreciate it. This problem makes no sense to me, the code should be identical.

© Stack Overflow or respective owner

Related posts about java

Related posts about listener