Java – How to “do something” on Swing component resizing


I've a class which extends JPanel. I overwrote protected void paintComponent(Graphics g).

There is a variable which has to be recalculated when the panel's dimensions change. How do I do that in a proper way?

Best Solution

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