How to “do something” on Swing component resizing?

后端 未结 8 1195
遇见更好的自我
遇见更好的自我 2021-01-17 07:53

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

There is a variable which has to be recalculate

8条回答
  •  孤独总比滥情好
    2021-01-17 08:21

    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();
    

提交回复
热议问题