Search code examples
sizejpanelpaintcomponent

setPreferreSize() in paintComponent


I am calculating the width of a JPanel from within its paintComponent() method. The calculation works, but the JPanel doesn´t have the preferred size. If I resize the window, everything is like it is supposed to be and the JPanel has the right size. I was trying to put the repaint() method in different places (e.g. in the constructor of the JPanel or the JFrame it is enbedded in), but I didn´t find a solution, that would show the frame with the correct size.

public void paintComponent(Graphics g) {
 super.paintComponent(g);
 g.setFont(new Font("SANS_SERIF",Font.PLAIN,14));
 FontMetrics metrics;
 ...  

 boxwidth = ... dependent on width and height of some Strings

 ...

 if (getPreferredSize().getWidth()<boxwidth+100){
 setPreferredSize(new Dimension(boxwidth+100,600));
 }

 ... 

}

I would like to know, wheter I can set the preferred size from within the paintComponent() method or if I can get the metrics somehow else, to be able to calculate boxwidth outside of paintComponent().

Thanks, Michael.


Solution

  • Call pack() on your JFrame after you've set preferred sizes, it will resize the JFrame to fit preferred sizes of all sub-components, it's quite annoying how well hidden that method is.

    http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#pack()