Determine size of panel before Graphics object is available

Hello everyone,

I have a JPanel with borderlayout set-up in it.

I have the following code:

jPanel.add(yAxisJPanel, BorderLayout.WEST);

jPanel.add(graphDisplay, BorderLayout.CENTER);

The problem I'm having is that I want the width of the yAxisJPanel to fit exactly the labels that are in it (the y axis labels). I'm currently able to achive this using font metrics and the graphics object in the paint component method of the yAxisJPanel.

However, the problem I'm having is that once the yAxisJPanel gets resized in the paint component method (since this is where I finally get my hands on the graphics object) there now becomes a gap between the West component which has been resized during it's paintComponent method (the y axis) and the Center component(the main display graph panel). How can I get the display to be drawn correctly (to fill this gap). ?

[903 byte] By [bythabayplayera] at [2007-11-26 21:38:06]
# 1

> I want the width of the yAxisJPanel to fit exactly the labels that are in it (the y axis labels)

That is the way LayoutManagers work. You add the lablels to the panel. The LayoutManager will then determine the appropriate width of the panel based on the widths of the components added to the panel.

So you must be doing something strange for it not to work.

If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program[/url] (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags[/url] so the posted code retains its original formatting.

camickra at 2007-7-10 3:20:51 > top of Java-index,Desktop,Core GUI APIs...
# 2

you must be doing something strange

Yup. It's this:

"the West component which has been resized during it's paintComponent method"

The paintComponent() method should be used for painting the component. The layoutContainer() method of LayoutManager should be used for setting the sizes of components.

There are no reasons to implement anything other than this exact policy, and doing so will only get you into the sort of situation in which you've found yourself.

itchyscratchya at 2007-7-10 3:20:51 > top of Java-index,Desktop,Core GUI APIs...