Java Swing How to - Add a scroll bar to a JTabbedPane








Question

We would like to know how to add a scroll bar to a JTabbedPane.

Answer

import java.awt.Color;
import java.awt.Dimension;
//www .j a v  a  2 s  .  c  o  m
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;

public class Main {
  public static void main(String[] args) {
    JPanel panel = new JPanel();
    Box box = Box.createVerticalBox();
    for (int i = 0; i < 100; i++) {
      box.add(new JLabel("Hello!"));
    }
    panel.add(box);

    JTabbedPane tab = new JTabbedPane();
    JScrollPane scroll = new JScrollPane(panel);
    scroll.setPreferredSize(new Dimension(300, 300));
    tab.add(scroll, "Panel 1");

    JOptionPane.showMessageDialog(null, tab, "Test Tabbed",
        JOptionPane.PLAIN_MESSAGE);
  }
}