How can we highlight the selected tab of a JTabbedPane in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JTabbedPane is a subclass of 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. We can highlight a selected tab with a particular color of a JTabbedPane by using the static method put() of the UIManager class.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SelectedJTabbedPaneTest extends JFrame implements ActionListener {
   private JTabbedPane tabbedPane;
   int tab = 0;
   public SelectedJTabbedPaneTest() {
      setTitle("SelectedJTabbedPane Test");
      setLayout(new BorderLayout());
      UIManager.put("TabbedPane.selected", Color.gray); // set the color of selected tab to gray 
      tabbedPane = new JTabbedPane();
      createTab();
      add(tabbedPane, BorderLayout.CENTER);
      setJMenuBar(createMenuBar());
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("JTabbedPane");
      JMenuItem menuItem = new JMenuItem("Create a new tab");
      menuItem.addActionListener(this);
      menu.add(menuItem);
      menuBar.add(menu);
      return menuBar;
   }
   public void actionPerformed(ActionEvent ae) {
      if (ae.getActionCommand().equals("Create a new tab")) {
         createTab();
      }
   }
   public void createTab() {
      tab++;
      tabbedPane.addTab("Tab " + tab, new JLabel("Tab " + tab));
   }
   public static void main(String []args) {
      new SelectedJTabbedPaneTest() ;
   }
}

Output

raja
Published on 22-Jul-2019 18:50:15
Advertisements