Java Swing How to - Layout with FlowLayout Preferred Size








Question

We would like to know how to layout with FlowLayout Preferred Size.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
// w  w w.  ja va  2  s .c  o m
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));

    JPanel navigation_panel_wrap = new JPanel() {
      @Override
      public Dimension getPreferredSize() {
        return new Dimension(250, 700);
      }
    };
    JPanel content_panel_wrap = new JPanel() {
      @Override
      public Dimension getPreferredSize() {
        return new Dimension(750, 700);
      }
    };

    content_panel_wrap.setBackground(Color.green);
    navigation_panel_wrap.setBackground(Color.red);

    frame.add(navigation_panel_wrap);
    frame.add(content_panel_wrap);
    frame.pack();
    frame.setVisible(true);

  }
}