Swing Component - disabling resizing in the layout

I have my own GUI compiler that is based on Swing JPanel. This component is placed in a JFrame that uses BorderLayout. When I resize the frame, this component saves the size. How can i avoid this? I would like the component to keep the same size. I tried setSize, setPreferredSize, setMinimumSize without success.

Thanks in advance!

M

+4
source share
3 answers

You have several options:

  • Customize the component in the internal panel using the LayoutManager , which does not resize your component.

  • Use a more sophisticated LayoutManager than BorderLayout . It seems to me that GridBagLayout better suited to your needs.

An example of the first solution:

 import java.awt.*; import javax.swing.*; public class FrameTestBase extends JFrame { public static void main(String args[]) { FrameTestBase t = new FrameTestBase(); JPanel mainPanel = new JPanel(new BorderLayout()); // Create some component JLabel l = new JLabel("hello world"); l.setOpaque(true); l.setBackground(Color.RED); JPanel extraPanel = new JPanel(new FlowLayout()); l.setPreferredSize(new Dimension(100, 100)); extraPanel.setBackground(Color.GREEN); // Instead of adding l to the mainPanel (BorderLayout), // add it to the extra panel extraPanel.add(l); // Now add the extra panel instead of l mainPanel.add(extraPanel, BorderLayout.CENTER); t.setContentPane(mainPanel); t.setDefaultCloseOperation(EXIT_ON_CLOSE); t.setSize(400, 200); t.setVisible(true); } } 

Result:

enter image description here

The green component is placed in BorderLayout.CENTER , the red component supports the preferred size.

+6
source
 //this will restrict size on fix size, what ever size you will define for panel like //panel.setSize(400,400); panel.setMaximumSize(panel.getSize()); panel..setMinimumSize(panel.getSize()); 
0
source

if you use your own layout manager, change the current layout to GridBagLayout and change the fill options to NONE , then change it to your first layout.

0
source

All Articles