tags:

views:

738

answers:

3

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?

Thanks in advance

+2  A: 

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);
jjnguy
+1  A: 

If I understand the question correctly then you should read the section from the Swing tutorial on How to Write a Component Listener which shows you how to listen for a change in a components size.

camickr
+4  A: 

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

}
Adam Paynter
This looks like the better way to go.
jjnguy
However, if the component is resized, but it isn't being painted, you may not wanna re calculate anything yet
jjnguy
Wow, shafted. I would have accepted your answer btw...
jjnguy
Thanks for the support. A bit odd that mine is actually an implementation of the accepted answer...
Adam Paynter