Java Swing How to - Make BoxLayout manager to layout dynamically created JTextArea








Question

We would like to know how to make BoxLayout manager to layout dynamically created JTextArea.

Answer

import java.awt.Component;
import java.awt.Dimension;
/*from  w ww .  jav a2s  .  co m*/
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends Box {
  Box container;
  Dimension minSize = new Dimension(400, 300);

  public Main(int axis) {
    super(BoxLayout.Y_AXIS);
    container = new Box(axis);
    container.setAlignmentX(Box.LEFT_ALIGNMENT);
    add(container);

    JTextArea text = new JTextArea();
    container.add(new JScrollPane(text));

    JButton split = new JButton("Split");
    split.setAlignmentX(Box.LEFT_ALIGNMENT);
    split.addActionListener(e->{
        JTextArea t = new JTextArea();
        container.add(new JScrollPane(t));
        revalidate();
    });
    add(split);

    JButton axisChanger = new JButton("Change Axis");
    axisChanger.setAlignmentX(Box.LEFT_ALIGNMENT);
    axisChanger.addActionListener(e->{
        Box newContainer;
        if (((BoxLayout) container.getLayout()).getAxis() == BoxLayout.X_AXIS) {
          newContainer = Box.createVerticalBox();
        } else {
          newContainer = Box.createHorizontalBox();
        }
        for (Component c : container.getComponents()) {
          container.remove(c);
          newContainer.add(c);
        }
        remove(container);
        add(newContainer, 0);
        container = newContainer;
        container.setAlignmentX(Box.LEFT_ALIGNMENT);
        revalidate();
    });
    add(axisChanger);

  }

  @Override
  public Dimension getPreferredSize() {
    Dimension result = super.getPreferredSize();
    result.width = result.width > minSize.width ? result.width : minSize.width;
    result.height = result.height > minSize.height ? result.height
        : minSize.height;
    return result;
  }

  public static void main(String[] args) {
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Main(BoxLayout.X_AXIS));
    frame.pack();
    frame.setVisible(true);
  }

}