Java Tutorial/Swing/JTabbedPane

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Add a tab with a label and icon at the end of all tabs

   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   JButton component = new JButton("button");
   Icon icon = new ImageIcon("icon.gif");
   pane.addTab("label", icon, component);
 }

}</source>





Add a tab with a label at the end of all tabs

   <source lang="java">

import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   JButton component = new JButton("button");
   String label = "Tab Label";
   pane.addTab(label, component);
 }

}</source>





Add a tab with a label, icon, and tool tip at the end of all tabs

   <source lang="java">

import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   JButton component = new JButton("button");
   String tooltip = "Tool Tip Text";
   pane.addTab("label", new ImageIcon("icon.png"), component, tooltip);
 }

}</source>





Add a tab with a label taken from the name of the component

   <source lang="java">

import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   JButton component = new JButton("button");
   component.setName("Tab Label");
   pane.add(component);
 }

}</source>





Add Button to tab bar

   <source lang="java">

import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; public class AddButtonToTabBar extends JFrame {

 private JTabbedPane tp;
 private JLabel lblStatus;
 private int tabCounter = 0;
 public AddButtonToTabBar() {
   super("Browser");
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   JMenuBar mb = new JMenuBar();
   JMenu mFile = new JMenu("File");
   JMenuItem mi = new JMenuItem("Add Tab");
   ActionListener addTabl = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       addTab();
     }
   };
   mi.addActionListener(addTabl);
   mFile.add(mi);
   mb.add(mFile);
   setJMenuBar(mb);
   JPanel pnlURL = new JPanel();
   tp = new JTabbedPane();
   addTab();
   getContentPane().add(tp, BorderLayout.CENTER);
   lblStatus = new JLabel(" ");
   getContentPane().add(lblStatus, BorderLayout.SOUTH);
   setSize(300, 300);
   setVisible(true);
 }
 void addTab() {
   JEditorPane ep = new JEditorPane();
   ep.setEditable(false);
   tp.addTab(null, new JScrollPane(ep));
   JButton tabCloseButton = new JButton("Close");
   tabCloseButton.setActionCommand("" + tabCounter);
   ActionListener al;
   al = new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
       JButton btn = (JButton) ae.getSource();
       String s1 = btn.getActionCommand();
       for (int i = 1; i < tp.getTabCount(); i++) {
         JPanel pnl = (JPanel) tp.getTabComponentAt(i);
         btn = (JButton) pnl.getComponent(0);
         String s2 = btn.getActionCommand();
         if (s1.equals(s2)) {
           tp.removeTabAt(i);
           break;
         }
       }
     }
   };
   tabCloseButton.addActionListener(al);
   if (tabCounter != 0) {
     JPanel pnl = new JPanel();
     pnl.setOpaque(false);
     pnl.add(tabCloseButton);
     tp.setTabComponentAt(tp.getTabCount() - 1, pnl);
     tp.setSelectedIndex(tp.getTabCount() - 1);
   }
   tabCounter++;
 }
 public static void main(String[] args) {
   new AddButtonToTabBar();
 }

}</source>





Add Components to JTabbedPane

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; public class JDK6TabbedPaneExample {

 private JFrame frame = new JFrame();
 private JTabbedPane tabbedPane = new JTabbedPane();
 private JButton addTabButton = new JButton("Add Tab");
 private ImageIcon closeXIcon = new ImageIcon("C:/CloseX.gif");
 private Dimension closeButtonSize;
 private int tabCounter = 0;
 public JDK6TabbedPaneExample() {
   addTabButton.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent e){
       add();
       
     }
     
   });
   closeButtonSize = new Dimension(closeXIcon.getIconWidth() + 2, closeXIcon.getIconHeight() + 2);
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.add(addTabButton, BorderLayout.SOUTH);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.pack();
   frame.setMinimumSize(new Dimension(300, 300));
   frame.setVisible(true);
 }
 public void add() {
   final JPanel content = new JPanel();
   JPanel tab = new JPanel();
   tab.setOpaque(false);
   JLabel tabLabel = new JLabel("Tab " + (++tabCounter));
   JButton tabCloseButton = new JButton(closeXIcon);
   tabCloseButton.setPreferredSize(closeButtonSize);
   tabCloseButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       int closeTabNumber = tabbedPane.indexOfComponent(content);
       tabbedPane.removeTabAt(closeTabNumber);
     }
   });
   tab.add(tabLabel, BorderLayout.WEST);
   tab.add(tabCloseButton, BorderLayout.EAST);
   tabbedPane.addTab(null, content);
   tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, tab);
 }
 public static void main(String[] args) {
   JDK6TabbedPaneExample main = new JDK6TabbedPaneExample();
 }

}</source>





Adding and Removing Tabs

  1. public void addTab(String title, Component component)
  2. public void addTab(String title, Icon icon, Component component)
  3. public void addTab(String title, Icon icon, Component component, String tip)
  4. public void insertTab(String title, Icon icon, Component component, String tip, int index)



   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class TabSample {

 static Color colors[] = { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE,
     Color.MAGENTA };
 static void add(JTabbedPane tabbedPane, String label) {
   int count = tabbedPane.getTabCount();
   JButton button = new JButton(label);
   button.setBackground(colors[count]);
   tabbedPane.addTab(label, new ImageIcon("yourFile.gif"), button, label);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Tabbed Pane Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
   String titles[] = { "A", "B", "C", "D", "E", "F" };
   for (int i = 0, n = titles.length; i < n; i++) {
     add(tabbedPane, titles[i]);
   }
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.setSize(400, 150);
   frame.setVisible(true);
 }

}</source>





Adds tool tips to a table using a renderer

   <source lang="java">

/*

*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/

import java.awt.ruponent; import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; public class TableRenderDemo extends JPanel {

 private boolean DEBUG = false;
 public TableRenderDemo() {
   super(new GridLayout(1, 0));
   JTable table = new JTable(new MyTableModel());
   table.setPreferredScrollableViewportSize(new Dimension(500, 70));
   // Create the scroll pane and add the table to it.
   JScrollPane scrollPane = new JScrollPane(table);
   // Set up column sizes.
   initColumnSizes(table);
   // Fiddle with the Sport column"s cell editors/renderers.
   setUpSportColumn(table, table.getColumnModel().getColumn(2));
   // Add the scroll pane to this panel.
   add(scrollPane);
 }
 /*
  * This method picks good column sizes. If all column heads are wider than the
  * column"s cells" contents, then you can just use column.sizeWidthToFit().
  */
 private void initColumnSizes(JTable table) {
   MyTableModel model = (MyTableModel) table.getModel();
   TableColumn column = null;
   Component comp = null;
   int headerWidth = 0;
   int cellWidth = 0;
   Object[] longValues = model.longValues;
   TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
   for (int i = 0; i < 5; i++) {
     column = table.getColumnModel().getColumn(i);
     comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false,
         false, 0, 0);
     headerWidth = comp.getPreferredSize().width;
     comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table,
         longValues[i], false, false, 0, i);
     cellWidth = comp.getPreferredSize().width;
     if (DEBUG) {
       System.out.println("Initializing width of column " + i + ". " + "headerWidth = "
           + headerWidth + "; cellWidth = " + cellWidth);
     }
     // XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
     column.setPreferredWidth(Math.max(headerWidth, cellWidth));
   }
 }
 public void setUpSportColumn(JTable table, TableColumn sportColumn) {
   // Set up the editor for the sport cells.
   JComboBox comboBox = new JComboBox();
   comboBox.addItem("Snowboarding");
   comboBox.addItem("Rowing");
   comboBox.addItem("Knitting");
   comboBox.addItem("Speed reading");
   comboBox.addItem("Pool");
   comboBox.addItem("None of the above");
   sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
   // Set up tool tips for the sport cells.
   DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
   renderer.setToolTipText("Click for combo box");
   sportColumn.setCellRenderer(renderer);
 }
 class MyTableModel extends AbstractTableModel {
   private String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };
   private Object[][] data = {
       { "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false) },
       { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
       { "Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false) },
       { "Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true) },
       { "Philip", "Milne", "Pool", new Integer(10), new Boolean(false) } };
   public final Object[] longValues = { "Sharon", "Campione", "None of the above",
       new Integer(20), Boolean.TRUE };
   public int getColumnCount() {
     return columnNames.length;
   }
   public int getRowCount() {
     return data.length;
   }
   public String getColumnName(int col) {
     return columnNames[col];
   }
   public Object getValueAt(int row, int col) {
     return data[row][col];
   }
   /*
    * JTable uses this method to determine the default renderer/ editor for
    * each cell. If we didn"t implement this method, then the last column would
    * contain text ("true"/"false"), rather than a check box.
    */
   public Class getColumnClass(int c) {
     return getValueAt(0, c).getClass();
   }
   /*
    * Don"t need to implement this method unless your table"s editable.
    */
   public boolean isCellEditable(int row, int col) {
     // Note that the data/cell address is constant,
     // no matter where the cell appears onscreen.
     if (col < 2) {
       return false;
     } else {
       return true;
     }
   }
   /*
    * Don"t need to implement this method unless your table"s data can change.
    */
   public void setValueAt(Object value, int row, int col) {
     if (DEBUG) {
       System.out.println("Setting value at " + row + "," + col + " to " + value
           + " (an instance of " + value.getClass() + ")");
     }
     data[row][col] = value;
     fireTableCellUpdated(row, col);
     if (DEBUG) {
       System.out.println("New value of data:");
       printDebugData();
     }
   }
   private void printDebugData() {
     int numRows = getRowCount();
     int numCols = getColumnCount();
     for (int i = 0; i < numRows; i++) {
       System.out.print("    row " + i + ":");
       for (int j = 0; j < numCols; j++) {
         System.out.print("  " + data[i][j]);
       }
       System.out.println();
     }
   }
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame("TableRenderDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // Create and set up the content pane.
   TableRenderDemo newContentPane = new TableRenderDemo();
   newContentPane.setOpaque(true); // content panes must be opaque
   frame.setContentPane(newContentPane);
   // Display the window.
   frame.pack();
   frame.setVisible(true);
 }

}</source>





Add user icon to tab panel

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JTabbedPane; import javax.swing.JTextField; public class TabPanelwithImageIconCustom extends JFrame {

 private JTextField textfield = new JTextField();
 public static void main(String[] args) {
   TabPanelwithImageIconCustom that = new TabPanelwithImageIconCustom();
   that.setVisible(true);
 }
 public TabPanelwithImageIconCustom() {
   setSize(450, 350);
   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   getContentPane().add(textfield, BorderLayout.SOUTH);
   JMenuBar mbar = new JMenuBar();
   JMenu menu = new JMenu("File");
   menu.add(new JCheckBoxMenuItem("Check Me"));
   menu.addSeparator();
   JMenuItem item = new JMenuItem("Exit");
   item.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.exit(0);
     }
   });
   menu.add(item);
   mbar.add(menu);
   setJMenuBar(mbar);
   JTabbedPane tabbedPane = new JTabbedPane();
   tabbedPane.addTab("Button", 
       new TabIcon(), 
       new JButton(""), 
       "Click here for Button demo"); 
 }

} class TabIcon implements Icon {

 public int getIconWidth() {
   return 16;
 }
 public int getIconHeight() {
   return 16;
 }
 public void paintIcon(Component c, Graphics g, int x, int y) {
   g.setColor(Color.black);
   g.fillRect(x + 4, y + 4, getIconWidth() - 8, getIconHeight() - 8);
   g.setColor(Color.cyan);
   g.fillRect(x + 6, y + 6, getIconWidth() - 12, getIconHeight() - 12);
 }

}</source>





Changing background, foreground and icon

  1. public void setBackgroundAt(int index, Color background)
  2. public void setForegroundAt(int index, Color foreground)
  3. public void setEnabledAt(int index, boolean enabled)
  4. public void setDisabledIconAt(int index, Icon disabledIcon)



   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; public class TabSample {

 static Color colors[] = { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE,
     Color.MAGENTA };
 static void add(JTabbedPane tabbedPane, String label, int mnemonic) {
   int count = tabbedPane.getTabCount();
   JButton button = new JButton(label);
   tabbedPane.addTab(label, new ImageIcon("yourFile.gif"), button, label);
   tabbedPane.setMnemonicAt(count, mnemonic);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Tabbed Pane Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   String titles[] = { "General", "Security", "Content", "Connection", "Programs", "Advanced" };
   int mnemonic[] = { KeyEvent.VK_G, KeyEvent.VK_S, KeyEvent.VK_C, KeyEvent.VK_O, KeyEvent.VK_P,
       KeyEvent.VK_A };
   for (int i = 0, n = titles.length; i < n; i++) {
     add(tabbedPane, titles[i], mnemonic[i]);
     tabbedPane.setBackgroundAt(i,colors[i]);
   }
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.setSize(400, 150);
   frame.setVisible(true);
 }

}</source>





Changing tab"s title, icon, mnemonic, tooltip, or component on a particular tab with one of the setXXXAt() methods

The displayed mnemonic index refers to which time a particular character in the title should be highlighted. In addition, you can change the background or foreground of a specific tab, enable or disable a specific tab, or have a different disabled icon with additional setXXXAt() methods:

  1. public void setTitleAt(int index, String title)
  2. public void setIconAt(int index, Icon icon)
  3. public void setMnemonicAt(int index, int mnemonic)
  4. public void setDisplayedMnemonicIndexAt(int index, int mnemonicIndex)
  5. public void setToolTipTextAt(int index, String text)
  6. public void setComponentAt(int index, Component component)



   <source lang="java">

import java.awt.BorderLayout; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; public class TabSample {

 static void add(JTabbedPane tabbedPane, String label, int mnemonic) {
   int count = tabbedPane.getTabCount();
   JButton button = new JButton(label);
   tabbedPane.addTab(label, new ImageIcon("yourFile.gif"), button, label);
   tabbedPane.setMnemonicAt(count, mnemonic);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Tabbed Pane Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   String titles[] = { "General", "Security", "Content", "Connection", "Programs", "Advanced" };
   int mnemonic[] = { KeyEvent.VK_G, KeyEvent.VK_S, KeyEvent.VK_C, KeyEvent.VK_O, KeyEvent.VK_P,
       KeyEvent.VK_A };
   for (int i = 0, n = titles.length; i < n; i++) {
     add(tabbedPane, titles[i], mnemonic[i]);
   }
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.setSize(400, 150);
   frame.setVisible(true);
 }

}</source>





Customizing a JTabbedPane Look and Feel

Property StringObject TypeTabbedPane.actionMapActionMapTabbedPane.ancestorInputMapInputMapTabbedPane.backgroundColorTabbedPane.borderHightlightColorColorTabbedPane.contentAreaColorColorTabbedPane.contentBorderInsetsInsetsTabbedPane.contentOpaqueBooleanTabbedPane.darkShadowColorTabbedPane.focusColorTabbedPane.focusInputMapInputMapTabbedPane.fontFontTabbedPane.foregroundColorTabbedPane.highlightColorTabbedPane.lightColorTabbedPane.opaqueBooleanTabbedPane.selectedColorTabbedPane.selectedForegroundColorTabbedPane.selectedTabPadInsetsInsetsTabbedPane.selectHighlightColorTabbedPane.selectionFollowsFocusBooleanTabbedPane.shadowColorTabbedPane.tabAreaBackgroundColorTabbedPane.tabAreaInsetsInsetsTabbedPane.tabInsetsInsetsTabbedPane.tabRunOverlayIntegerTabbedPane.tabsOpaqueBooleanTabbedPane.tabsOverlapBorderBooleanTabbedPane.textIconGapIntegerTabbedPane.unselectedBackgroundColorTabbedPane.unselectedTabBackgroundColorTabbedPane.unselectedTabForegroundColorTabbedPane.unselectedTabHighlightColorTabbedPane.unselectedTabShadowColorTabbedPaneUIString


Determining When the Selected Tab Changes in a JTabbedPane Container

   <source lang="java">

import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   pane.addChangeListener(new ChangeListener() {
     public void stateChanged(ChangeEvent evt) {
       JTabbedPane pane = (JTabbedPane) evt.getSource();
       int sel = pane.getSelectedIndex();
       System.out.println(sel);
     }
   });
 }

}</source>





Enable Scrolling Tabs in a JTabbedPane Container

   <source lang="java">

import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   int rows = pane.getTabRunCount();
   int policy = pane.getTabLayoutPolicy(); // WRAP_TAB_LAYOUT
   pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
 }

}</source>





Enabling and Disabling a Tab in a JTabbedPane Container

   <source lang="java">

import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   pane.addTab("Tab Label", new JButton("Button"));
   // Get index of the new tab
   int index = pane.getTabCount() - 1;
   // Determine whether the tab is enabled
   boolean enabled = pane.isEnabledAt(index);
   // Disable the tab
   pane.setEnabledAt(index, false);
 }

}</source>





Enabling the Selection of a Tab in a JTabbedPane Container Using a Keystroke

   <source lang="java">

import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   pane.addTab("Tab Label", new JButton("button"));
   int index = pane.getTabCount() - 1;
   int keycode = KeyEvent.VK_L;
   pane.setMnemonicAt(index, keycode);
 }

}</source>





First usage of JTabbedPane

   <source lang="java">

import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; public class MainClass {

 public static void main(String[] a) {
   JFrame f = new JFrame();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.add(new JTabbedPaneDemo());
   f.setSize(500, 500);
   f.setVisible(true);
 }

} class JTabbedPaneDemo extends JPanel {

 public void init() {
   try {
     SwingUtilities.invokeAndWait(new Runnable() {
       public void run() {
         makeGUI();
       }
     });
   } catch (Exception exc) {
     System.out.println("Can"t create because of " + exc);
   }
 }
 private void makeGUI() {
   JTabbedPane jtp = new JTabbedPane();
   jtp.addTab("Cities", new CitiesPanel());
   jtp.addTab("Colors", new ColorsPanel());
   jtp.addTab("Flavors", new FlavorsPanel());
   add(jtp);
 }

} class CitiesPanel extends JPanel {

 public CitiesPanel() {
   JButton b1 = new JButton("New York");
   add(b1);
   JButton b2 = new JButton("London");
   add(b2);
   JButton b3 = new JButton("Hong Kong");
   add(b3);
   JButton b4 = new JButton("Tokyo");
   add(b4);
 }

} class ColorsPanel extends JPanel {

 public ColorsPanel() {
   JCheckBox cb1 = new JCheckBox("Red");
   add(cb1);
   JCheckBox cb2 = new JCheckBox("Green");
   add(cb2);
   JCheckBox cb3 = new JCheckBox("Blue");
   add(cb3);
 }

} class FlavorsPanel extends JPanel {

 public FlavorsPanel() {
   JComboBox jcb = new JComboBox();
   jcb.addItem("Vanilla");
   jcb.addItem("Chocolate");
   jcb.addItem("Strawberry");
   add(jcb);
 }

}</source>





Get the index of the first tab that matches an icon

   <source lang="java">

import javax.swing.ImageIcon; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   ImageIcon icon = null;
   int index = pane.indexOfTab(icon);
 }

}</source>





Get the index of the tab by matching the child component

   <source lang="java">

import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   JButton component = new JButton("button");
   int index = pane.indexOfComponent(component);
   if (index < 0) {
     // The tab could not be found
   }
 }

}</source>





Getting and Setting the Selected Tab in a JTabbedPane Container

   <source lang="java">

import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   // Get the index of the currently selected tab
   int selIndex = pane.getSelectedIndex();
   // Select the last tab
   selIndex = pane.getTabCount() - 1;
   pane.setSelectedIndex(selIndex);
 }

}</source>





Getting the Tabs in a JTabbedPane Container

   <source lang="java">

import java.awt.ruponent; import javax.swing.Icon; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   int count = pane.getTabCount();
   for (int i = 0; i < count; i++) {
     String label = pane.getTitleAt(i);
     Icon icon = pane.getIconAt(i);
     String tooltip = pane.getToolTipTextAt(i);
     boolean enabled = pane.isEnabledAt(i);
     int keycode = pane.getMnemonicAt(i);
     Component comp = pane.getComponentAt(i);
   }
 }

}</source>





Insert a tab after the first tab

   <source lang="java">

import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   JButton component = new JButton("button");
   int index = 1;
   pane.insertTab("label", new ImageIcon("icon.png"), component, "tooltip", index);
 }

}</source>





JTabPane with TextField in the tab

   <source lang="java">

import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; public class TabSample {

 static void addIt(JTabbedPane tabbedPane, String text) {
   JLabel label = new JLabel(text);
   JButton button = new JButton(text);
   JPanel panel = new JPanel();
   panel.add(label);
   panel.add(button);
   tabbedPane.addTab(text, panel);
   tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, new JTextField(text));
 }
 public static void main(String args[]) {
   JFrame f = new JFrame("Got JTabbedPane?");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   addIt(tabbedPane, "Tab One");
   addIt(tabbedPane, "Tab Two");
   addIt(tabbedPane, "Tab Three");
   addIt(tabbedPane, "Tab Four");
   addIt(tabbedPane, "Tab Five");
   f.add(tabbedPane, BorderLayout.CENTER);
   f.setSize(300, 200);
   f.setVisible(true);
 }

}</source>





Listening for Selected Tab Changes

   <source lang="java">

import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class TabSample {

 static void add(JTabbedPane tabbedPane, String label) {
   JButton button = new JButton(label);
   tabbedPane.addTab(label, button);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Tabbed Pane Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   String titles[] = { "General", "Security", "Content", "Connection", "Programs", "Advanced" };
   for (int i = 0, n = titles.length; i < n; i++) {
     add(tabbedPane, titles[i]);
   }
   ChangeListener changeListener = new ChangeListener() {
     public void stateChanged(ChangeEvent changeEvent) {
       JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
       int index = sourceTabbedPane.getSelectedIndex();
       System.out.println("Tab changed to: " + sourceTabbedPane.getTitleAt(index));
     }
   };
   tabbedPane.addChangeListener(changeListener);
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.setSize(400, 150);
   frame.setVisible(true);
 }

}</source>





Moving a Tab in a JTabbedPane Container

   <source lang="java">

import java.awt.Color; import java.awt.ruponent; import javax.swing.Icon; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   int src = pane.getTabCount() - 1;
   int dst = 0;
   Component comp = pane.getComponentAt(src);
   String label = pane.getTitleAt(src);
   Icon icon = pane.getIconAt(src);
   Icon iconDis = pane.getDisabledIconAt(src);
   String tooltip = pane.getToolTipTextAt(src);
   boolean enabled = pane.isEnabledAt(src);
   int keycode = pane.getMnemonicAt(src);
   int mnemonicLoc = pane.getDisplayedMnemonicIndexAt(src);
   Color fg = pane.getForegroundAt(src);
   Color bg = pane.getBackgroundAt(src);
   pane.remove(src);
   pane.insertTab(label, icon, comp, tooltip, dst);
   pane.setDisabledIconAt(dst, iconDis);
   pane.setEnabledAt(dst, enabled);
   pane.setMnemonicAt(dst, keycode);
   pane.setDisplayedMnemonicIndexAt(dst, mnemonicLoc);
   pane.setForegroundAt(dst, fg);
   pane.setBackgroundAt(dst, bg);
 }

}</source>





New Methods in the JTabPane Component (Add component to JTabPane)

   <source lang="java">

import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; class TabComponent extends JPanel implements ActionListener {

 private JTabbedPane pane;
 public TabComponent(String title, JTabbedPane pane) {
   this.pane = pane;
   setOpaque(false);
   JLabel label = new JLabel(title);
   add(label);
   JButton button = new JButton("Close");
   button.setPreferredSize(new Dimension(50,10));
   button.addActionListener(this);
   add(button);
 }
 public void actionPerformed(ActionEvent e) {
   int i = pane.indexOfTabComponent(this);
   if (i != -1)
     pane.remove(i);
 }

} public class TabComponentDemo {

 public static void main(String[] args) {
   JTabbedPane pane = new JTabbedPane();
   String title = "Tab";
   pane.add(title, new JLabel(title));
   pane.setTabComponentAt(0, new TabComponent(title, pane));
   JFrame frame = new JFrame("Tab Component Demo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(pane);
   frame.setSize(500, 200);
   frame.setVisible(true);
 }

}</source>





Setting the Color of a Tab in a JTabbedPane Container

   <source lang="java">

import java.awt.Color; import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   pane.setForeground(Color.YELLOW);
   pane.setBackground(Color.MAGENTA);
   String label = "Tab Label";
   pane.addTab(label, new JButton("Button"));
   int index = pane.getTabCount() - 1;
   pane.setForegroundAt(index, Color.ORANGE);
   pane.setBackgroundAt(index, Color.GREEN);
 }

}</source>





Setting the Location of the Tabs in a JTabbedPane Container

   <source lang="java">

import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   int loc = pane.getTabPlacement(); 
   int location = JTabbedPane.LEFT; // or TOP, BOTTOM, RIGHT
   pane = new JTabbedPane(location);
   pane.setTabPlacement(JTabbedPane.BOTTOM);
 }

}</source>





Setting the Size of the Divider in a JSplitPane Container

   <source lang="java">

import javax.swing.JButton; import javax.swing.JSplitPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton leftComponent = new JButton("left"); 
   JButton rightComponent= new JButton("right");
 
   JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, rightComponent);
   int size = pane.getDividerSize();
   size = 1;
   pane.setDividerSize(size);
 }

}</source>





Setting the Tool Tip for a Tab in a JTabbedPane Container

   <source lang="java">

import javax.swing.JButton; import javax.swing.JTabbedPane; public class Main {

 public static void main(String[] argv) throws Exception {
   JTabbedPane pane = new JTabbedPane();
   String label = "Tab Label";
   String tooltip = "Tool Tip Text";
   pane.addTab(label, null, new JButton("Button"), tooltip);
   int index = pane.getTabCount() - 1;
   tooltip = pane.getToolTipTextAt(index);
   tooltip = "New Tool Tip Text";
   pane.setToolTipTextAt(index, tooltip);
 }

}</source>





Specifying a tab"s location: TOP, BOTTOM, LEFT, or RIGHT

   <source lang="java">

import java.awt.BorderLayout; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; public class TabLocation {

 static void add(JTabbedPane tabbedPane, String label, int mnemonic) {
   int count = tabbedPane.getTabCount();
   JButton button = new JButton(label);
   tabbedPane.addTab(label, new ImageIcon("yourFile.gif"), button, label);
   tabbedPane.setMnemonicAt(count, mnemonic);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Tabbed Pane Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   String titles[] = { "General", "Security", "Content", "Connection", "Programs", "Advanced" };
   int mnemonic[] = { KeyEvent.VK_G, KeyEvent.VK_S, KeyEvent.VK_C, KeyEvent.VK_O, KeyEvent.VK_P,
       KeyEvent.VK_A };
   for (int i = 0, n = titles.length; i < n; i++) {
     add(tabbedPane, titles[i], mnemonic[i]);
   }
   tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.setSize(400, 150);
   frame.setVisible(true);
 }

}</source>





TabLayout Policy: SCROLL_TAB_LAYOUT or WRAP_TAP_LAYOUT

   <source lang="java">

import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; public class TabSampleTabLayoutPolicy {

 static void add(JTabbedPane tabbedPane, String label) {
   JButton button = new JButton(label);
   tabbedPane.addTab(label, button);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Tabbed Pane Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
   String titles[] = { "General", "Security", "Content", "Connection", "Programs", "Advanced" };
   for (int i = 0, n = titles.length; i < n; i++) {
     add(tabbedPane, titles[i]);
   }
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.setSize(400, 150);
   frame.setVisible(true);
 }

}</source>





To remove a tab, you can remove a specific tab with removeTabAt(int index), remove(int index), or remove(Component component)

Removing all tabs with removeAll()



   <source lang="java">

import java.awt.BorderLayout; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; public class TabSampleRemoveAll {

 static void add(JTabbedPane tabbedPane, String label, int mnemonic) {
   int count = tabbedPane.getTabCount();
   JButton button = new JButton(label);
   tabbedPane.addTab(label, new ImageIcon("yourFile.gif"), button, label);
   tabbedPane.setMnemonicAt(count, mnemonic);
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Tabbed Pane Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTabbedPane tabbedPane = new JTabbedPane();
   tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
   String titles[] = { "General", "Security", "Content", "Connection", "Programs", "Advanced" };
   int mnemonic[] = { KeyEvent.VK_G, KeyEvent.VK_S, KeyEvent.VK_C, KeyEvent.VK_O, KeyEvent.VK_P,
       KeyEvent.VK_A };
   for (int i = 0, n = titles.length; i < n; i++) {
     add(tabbedPane, titles[i], mnemonic[i]);
   }
   tabbedPane.removeAll();
   frame.add(tabbedPane, BorderLayout.CENTER);
   frame.setSize(400, 150);
   frame.setVisible(true);
 }

}</source>