user1917209
user1917209

Reputation: 205

java JFrame resize

I have the following code segment in my project.

someJFrame.addComponentListener(new ComponentAdapter(){  
    public void componentResized(ComponentEvent e) {
    pane.resize(new Dimension(getSize().width/5, getSize().height/3));
    pane.revalidate();
    pane.repaint();
    }
});

It seems to call the componentResized() method right at the beginning when the JFrame is initialized for the first time, even though the user did not resize the JFrame- I need to prevent this from happening. I only want componetResized() to be called when a real resize has happent, and not at JFrame initialization.

Upvotes: 0

Views: 950

Answers (1)

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Here's the way to go-

  1. Define a boolean flag to indicate if the component is shown, default to false
  2. Override componentShown() and set this flag to true, this gets called when the frame is made visible
  3. In componentResized() check if componentShown flag is set, only then do something

Something like this-

    private boolean componentShown = false; // instance variable

    someJFrame.addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent e) {
            if(componentShown) {
               System.out.println("Component RESIZED");
            }  
        }

        public void componentShown(ComponentEvent e) {
            componentShown = true;
        }
    });

Upvotes: 1

Related Questions