Java Swing How to - Change tab name for JTabbedPane








Question

We would like to know how to change tab name for JTabbedPane.

Answer

import java.awt.BorderLayout;
//ww  w .j ava  2 s.c o m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class Main extends JFrame {
  JLabel jLabel1 = new JLabel("jLabel1");
  JLabel jLabel2 = new JLabel("jLabel2");
  JMenuItem jMenuItem1 = new JMenuItem("jMenuItem1");
  JPopupMenu jPopupMenu1 = new JPopupMenu();
  JTabbedPane jTabbedPane1 = new JTabbedPane();

  public Main() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(400, 300);    
    jPopupMenu1.add(jMenuItem1);
    jTabbedPane1.addTab(null, jLabel1);
    jTabbedPane1.addTab(null, jLabel2);
    getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
    int tabCount = jTabbedPane1.getTabCount();
    for (int i = 0; i < tabCount; i++) {
      JLabel jLabel = new JLabel("Testing the tab" + (i + 1));
      jTabbedPane1.setTabComponentAt(i, jLabel);
      jLabel.setName(String.valueOf(i));
      jLabel.setComponentPopupMenu(jPopupMenu1);
    }
    jPopupMenu1.addPopupMenuListener(new PopupMenuListener() {

      @Override
      public void popupMenuCanceled(final PopupMenuEvent evt) {
      }

      @Override
      public void popupMenuWillBecomeInvisible(final PopupMenuEvent evt) {
      }

      @Override
      public void popupMenuWillBecomeVisible(final PopupMenuEvent evt) {
        JPopupMenu source = (JPopupMenu) evt.getSource();
        JLabel invoker = (JLabel) source.getInvoker();
        JLabel component = (JLabel) jTabbedPane1.getComponentAt(Integer
            .parseInt(invoker.getName()));
        jMenuItem1.setText(invoker.getText() + ":  " + component.getText());
      }
    });
  }

  public static void main(final String args[]) {
    new Main().setVisible(true);
  }
}