Ameer Jewdaki
Ameer Jewdaki

Reputation: 1798

Window resize event?

I'm writing a simple painting program using Java, and I want some method to be called whenever the JFrame component is resized. However I can't find any method like windowResizedListener or an event like windowResizedEvent. What can I do?!

Upvotes: 46

Views: 80363

Answers (5)

maximusg
maximusg

Reputation: 143

To access the Window resize method event I implemented ComponentListener inside a subclass. This is a custom JPanel class you can use to write the window-size to a JLabel inside a GUI. Just implement this class in your main method and add it to your JFrame and you can resize the window and it will dynamically show you the Pixel size of your window. (Note you must add your JFrame object to the Class)

package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentListener;
public class DisplayWindowWidth extends JPanel{
JLabel display;
JFrame frame;
public DisplayWindowWidth(JFrame frame){
        display = new JLabel("---");
        this.frame = frame;
    
        frame.addComponentListener(new FrameListen());
        add(display);
        setBackground(Color.white);
    }

    private class FrameListen implements ComponentListener{
        public void componentHidden(ComponentEvent arg0) {
        }
        public void componentMoved(ComponentEvent arg0) {   
        }
        public void componentResized(ComponentEvent arg0) {
            String message = " Width: " +
            Integer.toString(frame.getWidth());
            display.setText(message);
        
        }
        public void componentShown(ComponentEvent arg0) {
        
        }
    }
}

Upvotes: 3

trashgod
trashgod

Reputation: 205875

Overriding particular methods of ComponentAdapter is a convenient alternative to implementing all the methods of ComponentListener. Several examples seen here illustrate the "convenience for creating listener objects" mentioned in the API.

Upvotes: 22

Yuval Adam
Yuval Adam

Reputation: 165340

Implement a ComponentAdapter with componentResized():

frame.addComponentListener(new ComponentAdapter() {
    public void componentResized(ComponentEvent componentEvent) {
        // do stuff
    }
});

Upvotes: 80

Eduardo Oliveros
Eduardo Oliveros

Reputation: 21

An example with ComponentAdapter

//Detect windows changes
window.addComponentListener(new ComponentAdapter( ) {
  public void componentResized(ComponentEvent ev) {
   label.setText(ev.toString());
  }
});

Upvotes: 2

Valentin Rocher
Valentin Rocher

Reputation: 11669

You have to use componentResized from ComponentListener.

Upvotes: 3

Related Questions