How can we insert multiple tabs into a single JTabbedPane in Java?


JTabbedPane

  • A JTabbedPane is a component can extend JComponent class and we can able to see one tab at a time.
  • Each tab is associated with a single component that can be displayed when the tab is selected.
  • A JTabbedPane can generate a ChangeListener interface when a tab is selected.
  • It is also possible to insert multiple tabs into a single JTabbedPane and the important methods of JTabbedPane are addTab(), fireStateChanged(), getTabPlacement(), setSelectedIndex(), getTabCount() and etc.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class NestedJTabbedPaneTest extends JFrame {
   public NestedJTabbedPaneTest() {
      setTitle("Nested JTabbedPane test");
      setLayout(new BorderLayout());
      JTabbedPane tabbedPane = new JTabbedPane();
      add(BorderLayout.CENTER, tabbedPane);
      createNestedTab(tabbedPane, 1);
      
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLoc*ationRelativeTo(null);
      setVisible(true);
   }
   protected void createNestedTab(JTabbedPane jtp, int count) {
      if (count > 5) return;
      JTabbedPane tp = new JTabbedPane();
      tp.setTabPlacement(getNextOrientation(jtp.getTabPlacement()));
      jtp.addTab("Tab #" + count, tp);
      createNestedTab(tp, count+1);
   }
   private int getNextOrientation(int tabPlacement) {
      if (tabPlacement == JTabbedPane.TOP) return JTabbedPane.RIGHT;
      if (tabPlacement == JTabbedPane.RIGHT) return JTabbedPane.BOTTOM;
      if (tabPlacement == JTabbedPane.BOTTOM) return JTabbedPane.LEFT;
      else return JTabbedPane.TOP;
   }
   public static void main(String []args) {
      new NestedJTabbedPaneTest();
   }
}

Output

raja
Published on 15-Jul-2019 08:25:11
Advertisements