Java trying to set Frame resizable(false) on the fly

66 views Asked by At

I'm working on an old java awt application and I try to change the resizable property of the main Frame by the code "on the fly" when needed. The problem is that I've got a ComponentListener linked to this Frame and when I disable then enable my Frame resizing, I loose the ComponentListener.

Here the piece of code I'm using to do that :

Frame constructor:

compListener = new ComponentListener() {
      public void componentShown(ComponentEvent arg0) {}
            
      public void componentResized(ComponentEvent arg0) {
           ScreenManager.windowResized(arg0.getComponent().getSize());
      }
            
      public void componentMoved(ComponentEvent arg0) {}
            
      public void componentHidden(ComponentEvent arg0) {}
};

addComponentListener(compListener); 

My method to enable/disable the resizable status of my frame:

public void setResizableStatus(boolean isResizable) {
     this.removeComponentListener(compListener);
     this.setResizable(isResizable);
     if (isResizable)
     {
         this.addComponentListener(compListener);
     }        
     this.revalidate();
     this.repaint();
}

What's wrong in my code?

2

There are 2 answers

0
GhostCat On

Simple: the code shown here does:

  • always remove the listener
  • not always re-add the listener

Thus the solution should be to:

if (isResizable)
{
    this.addComponentListener(compListener);
}      

remove that if-condition.

1
breizh punisher On

I've changed my code like this :

public void setResizableStatus(boolean isResizable)
{
    this.removeComponentListener(compListener);
    this.setResizable(isResizable);

    this.addComponentListener(compListener);
    
    this.revalidate();
    this.repaint();
}

But the result is the same, I loose my ComponentListener. I really don't know why.