javax.swing.Box

javax.swing.Boxが結構使い勝手がいい。

例えば、縦にボタンを並べたい場合は:

Box box = new Box(BoxLayout.PAGE_AXIS);
      
box.add(new JButton("button1"));
box.add(new JButton("button2"));
box.add(new JButton("button3"));
box.add(new JButton("button4"));
 
frame.add(box);

そして、一部横に並べたい場合は、

Box box = new Box(BoxLayout.PAGE_AXIS);
 
box.add(new JButton("button1"));
 
Box line = new Box(BoxLayout.LINE_AXIS);
line.add(new JButton("button2-1"));
line.add(new JButton("button2-2"));
box.add(line);
 
box.add(new JButton("button3"));
box.add(new JButton("button4"));
 
frame.add(box);

とする。


サンプルコード

import javax.swing.*;

public class BoxTest {
  public BoxTest(){
      JFrame frame = new JFrame("box test");
      Box box = new Box(BoxLayout.PAGE_AXIS);
      box.add(new JButton("button1"));
              
      Box line = new Box(BoxLayout.LINE_AXIS);
      line.add(new JButton("button2-1"));
      line.add(new JButton("button2-2"));
      box.add(line);
 
      box.add(new JButton("button3"));
      box.add(new JButton("button4"));
      frame.add(box);
 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setVisible(true);
  }
   
  public static void main(String[] args){
      new BoxTest();
  }
}