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