Add icon to a tab in JTabbedPane in Java

Description

The following code shows how to add icon to a tab in JTabbedPane.

Example


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
//from  w ww . j  a va  2  s  .co  m
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;

public class Main extends JFrame {
  public static void main(String[] args) {
    Main that = new Main();
    that.setVisible(true);
  }

  public Main() {
    setSize(450, 350);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTabbedPane tabbedPane = new JTabbedPane();

    tabbedPane.addTab("Button", 
        new TabIcon(), 
        new JButton(""), 
        "Click here for Button demo"); 
    
    getContentPane().add(tabbedPane, BorderLayout.CENTER);
  }
}
class TabIcon implements Icon {
  public int getIconWidth() {
    return 16;
  }

  public int getIconHeight() {
    return 16;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(Color.black);
    g.fillRect(x + 4, y + 4, getIconWidth() - 8, getIconHeight() - 8);
    g.setColor(Color.cyan);
    g.fillRect(x + 6, y + 6, getIconWidth() - 12, getIconHeight() - 12);
  }
}

The code above generates the following result.

Add icon to a tab 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