Set the Color of a Tab in a Tabbed Pane Container in Java

In this section, you will learn how to set colors for a tab in a tabbed pane container in Java Swing applications.

Set the Color of a Tab in a Tabbed Pane Container in Java

In this section, you will learn how to set colors for a tab in a tabbed pane container in Java Swing applications.

Set the Color of a Tab in a Tabbed Pane Container in Java

Set the Color of a Tab in a Tabbed Pane Container in Java

     

In this section, you will learn how to set colors for a tab in a tabbed pane container in Java Swing applications. Every tab and it's corresponding container can have different colors. Following screen shot of our example show the colorful tabs:

Colorful Tabs in a JTabbedPane component

This program shows you how to set the color for each tab in the tabbed pane container. Background color and foreground color for the tab and it's corresponding container component are set using following methods:

setForegroundAt(int Index, Color.color_name):
This is the method of JTabbedPane class is used to set the foreground color of the specified tab. This method takes two argument in which, first is the index number of the tab which has to be colored and another is the color which has to be set for the specific tab.

setBackgroundAt(int Index, Color.color_name):
This is the method of JTabbedPane class is used to set the background color of the specified tab. This method also takes two argument, first is the index number of the tab which background has to be colored and another is the color which has to be set for the background color of the specified tab.

Here is the code of program:

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

public class SetColorTab{
  JFrame frame;
  JTabbedPane tpane;
  JPanel panel;
  public static void main(String[] args) {
  SetColorTab c = new SetColorTab();
  }
  public SetColorTab(){
  frame = new JFrame("Setting the Color of a Tab in a 
JTabbedPane Container"
);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  tpane = new JTabbedPane();
  panel = new JPanel();
  tpane.addTab("Color", null, panel);
  panel = new JPanel();
  tpane.addTab("Hardware", null, panel);
  panel = new JPanel();
  tpane.addTab("Software", null, panel);
  panel = new JPanel();
  tpane.addTab("Network", null, panel);
  tpane.setForegroundAt(2, Color.RED);
  tpane.setBackgroundAt(2, Color.GRAY);
  tpane.setForegroundAt(1, Color.PINK);
  tpane.setBackgroundAt(1, Color.GREEN);
  frame.add(tpane);
  frame.setSize(400,400);
  frame.setVisible(true);
  }
}

Download this example