How to “do something” on Swing component resizing?

后端 未结 8 1186
遇见更好的自我
遇见更好的自我 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

    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) {}
    
    }
    

提交回复
热议问题