How do I assign tool tips for JTabbedPane tabs?

To set a tool tips for JTabbedPane‘s tabs you need to pass the tool tips when adding a new tab to the JTabbedPane. The addTab() method accept the following parameters: the tab’s title, image icon, a component that is going to be the content of the tabs and a string of tool tips information.

When you hover your mouse to the JTabbedPane‘s tabs the tool tips will be shown on the screen. Here is an example how you can can add tool tips the JTabbedPane‘s tabs.

package org.kodejava.swing;

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

public class TabbedPaneToolTips extends JPanel {
    public TabbedPaneToolTips() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TabbedPaneToolTips();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTabbedPane Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TabbedPaneToolTips::showFrame);
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));

        JTabbedPane pane = new JTabbedPane();
        ImageIcon tab1Icon = new ImageIcon(Objects.requireNonNull(
                this.getClass().getResource("/images/test-pass-icon.png")));
        ImageIcon tab2Icon = new ImageIcon(Objects.requireNonNull(
                this.getClass().getResource("/images/test-fail-icon.png")));
        ImageIcon tab3Icon = new ImageIcon(Objects.requireNonNull(
                this.getClass().getResource("/images/test-error-icon.png")));

        JPanel content1 = new JPanel();
        JPanel content2 = new JPanel();
        JPanel content3 = new JPanel();

        // Add tabs to the JTabbedPane. The last parameter in the
        // add tab method is the tool tips for the tabs.
        pane.addTab("Success", tab1Icon, content1, "Success Test Cases");
        pane.addTab("Fail", tab2Icon, content2, "Fail Test Cases");
        pane.addTab("Error", tab3Icon, content3, "Error Test Cases");

        this.add(pane, BorderLayout.CENTER);
    }
}

The result of the code snippet above is:

JTabbedPane Tabs’ Tool Tips Demo

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.