Change tab background in JTabbedPane in Java

Description

The following code shows how to change tab background in JTabbedPane.

Example


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyEvent;
//  w w  w .j  av a 2 s  . co m
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;

public class Main {
  static Color colors[] = { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE,
      Color.MAGENTA };

  static void add(JTabbedPane tabbedPane, String label, int mnemonic) {
    int count = tabbedPane.getTabCount();
    JButton button = new JButton(label);
    tabbedPane.addTab(label, new ImageIcon("yourFile.gif"), button, label);
    tabbedPane.setMnemonicAt(count, mnemonic);
  }

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

    JTabbedPane tabbedPane = new JTabbedPane();
    String titles[] = { "General", "Security", "Content", "Connection", "Programs", "Advanced" };
    int mnemonic[] = { KeyEvent.VK_G, KeyEvent.VK_S, KeyEvent.VK_C, KeyEvent.VK_O, KeyEvent.VK_P,
        KeyEvent.VK_A };
    for (int i = 0, n = titles.length; i < n; i++) {
      add(tabbedPane, titles[i], mnemonic[i]);
      tabbedPane.setBackgroundAt(i,colors[i]);
    }
    frame.add(tabbedPane, BorderLayout.CENTER);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Change tab background in 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