Hi All, I figured the swing folks could help me out with this one. I am having some confusion about how the setPrefferedSize() method works, or does it even work on JPanels? I want 2 panels, a north panel and a south panel, and I want each of them to share the JFrame equally. I have set their preffered size to be the same. When I run this sample code below, I only see the south panel. If I maximize the window, I can see the north panel, but only briefly. But, I can definitely tell that it is not in the right place. Can someone please tell me why this is happening? I am sure this is something simple, but I cannot figure out what. Many thanks to you!!!
You can use setPreferredSize() in BorderLayout also. The problem lies in the code, you are adding the same component to the other Panel & thats why you can't see the components in the North Panel. Use new Objects then u can see the components in the North Panel also.
Hi Barry, The reason is that each GUI component (AWT or Swing) keeps track of its own parent, bounds, etc. Knowing this we can say that an object can only be in one place at one time. The other reason is basic Java. Method parameters are passed by value in Java. What does that mean? It means that when we pass the value 'button1' into the add method we are actually receiving a copy of the reference to button1. We are still pointing to the object button1. Therefore, using the above reasoning we can see why the button1 state (parent, bounds, etc.) is changed inside the add method. Using the same or another reference to the same object will again change the button1 state. Therefore, a single object can only be in one state (in one container) at a single time. Long winded, but maybe effective? Manfred.
Another question along the same lines. If I had 2 buttons and I wanted to set the preferred size for each button to be different, would I need to create 2 Dimension objects or could I use the same one and just setSize() to something else? So something like this: Dimension d = new Dimension(50,30); JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); button1.setPrefferedSize(d); d.setSize(60,40); button2.setPrefferedSize(d); By changing the state of "d", I won't be also changing the state of button1. Is this correct?
Joined: Dec 06, 2000
You are right Barry, button1's properties have already been set, so it wont change.