How to “do something” on Swing component resizing?

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

    It resizes automatically if it's

    1. inside a BorderLayout panel and
    2. put there as BorderLayout.CENTER component.

    If it doesn't work, you probably have forgotten one of these two.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题