Java Swing How to - Disable resize in layout








Question

We would like to know how to disable resize in layout.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
// ww w  . ja va2s . c  om
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {

  public static void main(String args[]) {
    Main t = new Main();

    JPanel mainPanel = new JPanel(new BorderLayout());

    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);

    extraPanel.add(l);

    mainPanel.add(extraPanel, BorderLayout.CENTER);

    t.setContentPane(mainPanel);

    t.setDefaultCloseOperation(EXIT_ON_CLOSE);
    t.setSize(400, 200);
    t.setVisible(true);
  }
}