Reputation: 717
I have a ComponentListener
for the main JFrame
that sends an event when it is resized but by the time the event is fired, the Jpanel
has already been resized.
public class Test implements ComponentListener {
private JFrame frame;
private JPanel panel;
public Test() {
frame = new JFrame();
panel = new JPanel();
frame.setPreferredSize(new Dimension(300, 300));
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.addComponentListener(this);
frame.pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
Test test = new Test();
test.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void componentResized(ComponentEvent e) {
System.out.println(frame.getSize() + " : " + panel.getSize());
frame.revalidate();
}
@Override
public void componentHidden(ComponentEvent e) {}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentShown(ComponentEvent e) {}
}
How do I control JPanel setSize
during a JFrame
resize?
Edit: I understand BorderLayout
sets components to fill the border. How does it set the size of the component? Is it calling setSize
? if yes, why an overridden setSize called?
Upvotes: 2
Views: 3418
Reputation: 20059
You can't control a components size directly when it is added to a container under a LayoutManager's control. That defeats the purpose of using a layout manager.
If you want to be notified when a components size has changed, add a ComponentListener to the component (not the container).
Upvotes: 1
Reputation: 324108
Is it calling setSize?
Layout manager use getPreferredSize(), getMinimumSize() and getMaximum() size as hints. The layout manager and use or ignore these hints. When you add a component to the CENTER of the BorderLayout all the hints are ignored and the component is sized to the space available. So, yes, the layout manager will invoke the setSize() (and setLocation) methods of a component. You should not invoke the setSize() method directly
why isn't my overridden setSize called?
You did not override
the setSize() method. When you execute your code you invoked
the setSize() method. Then later the layout manager is invoked when the frame is packed() and the layout manager will invoke the setSize() method on the panel.
Upvotes: 1
Reputation: 803
You cannot resize a component in a BorderLayout if it's constraint is BorderLayout.CENTER. The component takes automatically all the available space.
More informations : http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
Upvotes: 0