Get and Set the Selected Tab in a JTabbedPane in Java

Description

The following code shows how to get and Set the Selected Tab in a JTabbedPane.

Example


  //from   w  w  w .  j a  v a 2 s  .  c  om
import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tabbed Pane Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTabbedPane tabbedPane = new JTabbedPane();
    JButton button = new JButton("a");
    tabbedPane.addTab("java2s.com", new JButton("a"));
    tabbedPane.addTab("java2s.com", button);

    // Get the index of the currently selected tab
    int selIndex = tabbedPane.getSelectedIndex();

    // Select the last tab
    selIndex = tabbedPane.getTabCount() - 1;
    tabbedPane.setSelectedIndex(selIndex);

    frame.add(tabbedPane, BorderLayout.CENTER);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Get and Set the Selected Tab in a JTabbedPane in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer