Java Swing How to - Change Tab layout policy for JTabbedPane








Question

We would like to know how to change Tab layout policy for JTabbedPane.

Answer

import java.awt.Dimension;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/* ww w .  ja v a  2 s .  com*/
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

public class Main extends JFrame {
  int tabNumber = 15;
  JTabbedPane pane = new JTabbedPane();
  JMenuItem tabComponentsItem;
  JMenuItem scrollLayoutItem;

  public Main(String title) {
    super(title);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar menuBar = new JMenuBar();
    tabComponentsItem = new JCheckBoxMenuItem("Use TabComponents", true);
    tabComponentsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
        InputEvent.ALT_MASK));
    tabComponentsItem.addActionListener(e -> {
      for (int i = 0; i < pane.getTabCount(); i++) {
        if (tabComponentsItem.isSelected()) {
        } else {
          pane.setTabComponentAt(i, null);
        }
      }
    });
    scrollLayoutItem = new JCheckBoxMenuItem("Set ScrollLayout");
    scrollLayoutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
        InputEvent.ALT_MASK));
    scrollLayoutItem.addActionListener(e -> {
      if (pane.getTabLayoutPolicy() == JTabbedPane.WRAP_TAB_LAYOUT) {
        pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
      } else {
        pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
      }
    });
    JMenuItem resetItem = new JMenuItem("Reset JTabbedPane");
    resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
        InputEvent.ALT_MASK));
    resetItem.addActionListener(e -> runTest());
    JMenu optionsMenu = new JMenu("Options");
    optionsMenu.add(tabComponentsItem);
    optionsMenu.add(scrollLayoutItem);
    optionsMenu.add(resetItem);
    menuBar.add(optionsMenu);
    setJMenuBar(menuBar);
    add(pane);
  }

  public void runTest() {
    pane.removeAll();
    for (int i = 0; i < tabNumber; i++) {
      String title = "Tab " + i;
      pane.add(title, new JLabel(title));
    }
    tabComponentsItem.setSelected(true);
    pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
    scrollLayoutItem.setSelected(false);
    setSize(new Dimension(400, 200));
    setLocationRelativeTo(null);
    setVisible(true);
  }

  public static void main(String[] args) {
    UIManager.put("swing.boldMetal", Boolean.FALSE);
    new Main("Main").runTest();
  }
}