How to "do something" on Swing component resizing?

Like Adam Paynter suggested, you can also add an inner class to your code, like this:

class ResizeListener extends ComponentAdapter {
        public void componentResized(ComponentEvent e) {
            // Recalculate the variable you mentioned
        }
}

The code you have entered between the innermost brackets will be executed everytime the component get resized.

Then you add this listener to your component with

myJPanel.addComponentListener(new ResizeListener());

You can get your component by using e.getComponent(). This way you can call any method of your component from inside the inner class like

e.getComponent().getWeight();

I suppose you could override the various setSize and resize methods and perform the calculation there. However, you may not find all the places where the size can be changed. You may want to have your class implement ComponentListener and simply listen to itself for resize events.

Warning: I am not a Swing expert.

Warning: I have not compiled this code.

public class MyJPanel extends JPanel implements ComponentListener {

    public MyJPanel() {
        this.addComponentListener(this);
    }

    public void paintComponent(Graphics g) {
        // Paint, paint, paint...
    }

    public void componentResized(ComponentEvent e) {
        // Perform calculation here
    }

    public void componentHidden(ComponentEvent e) {}

    public void componentMoved(ComponentEvent e) {}

    public void componentShown(ComponentEvent e) {}

}

Tags:

Java

Swing