How to “do something” on Swing component resizing?

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

    If the calculation isn't time consuming, I would just re-calculate the value each time in paintComponent().

    Otherwise, you can save a value that is the size of the component and check it against the new size in paintComponent. If the size changed, then recalculate, otherwise don't.

    private Dimension size;
    
    protected void paintComponent(Graphics g){
        if (!size.equals(getSize())){
            size = getSize();
            // recalculate value
        }
    }
    

    Or, you can do the calculation on a resize event.

    private CompoentListener resizeListener = new ComponentAdapter(){
        public void componentResized(ActionEvent e){
            // recalculate value
        }
    };
    
    //in the constructor add the line
    addComponentListener(resizeListener);
    

提交回复
热议问题