开发者

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

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();
private static JPanel imagePanel;

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.


Man camickr, you were right. Man this was a weird one to solve. There was something else wrong with my code. The order of the methods calls into my class resulted in me adding the listener then another method would end up removing the listener referenced by that variable so of course i would never get events. Thanks a lot for all the help ppl.


I think your problem is that you're declaring panelResizeListener after you're using it. That normally kills just about anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜