Tutorialspoint

1 Answer
raja ramesh

JTabbedPane
  • A JTabbedPane is a component can extend JComponent class and it can provide easy access to more than one panel.
  • 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.
  • The important methods of JTabbedPane are add(), addTab(), fireStateChanged(), createChangeListener(), setSelectedIndex(), getTabCount() and etc.

Example

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

public class JTabbedPaneTest extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
   public JTabbedPaneTest() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane();
      createTab();
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
      
      tabbedPane.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent ce) {
            System.out.println("Tab " + (tabbedPane.getSelectedIndex() + 1) + " is selected");
         }
      });

      setTitle("JTabbedPane Test");
      setLocationRelativeTo(null);
      setSize(new Dimension(350, 275));
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("JTabbedPane");
      JMenuItem menuItem = new JMenuItem("Create new tab");
      menuItem.addActionListener(this);
      menu.add(menuItem);
      menuBar.add(menu);
      return menuBar;
   }
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
   public static void main(String []args) {
      new JTabbedPaneTest();
   }
}

Output

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.