Swing ToolTip Tutorial with Example

In this tutorial, we will learn how to add tooltip text to a Swing component using the setToolTipText(String s) method.
javax.swing.JComponent.setToolTipText(String text) - This method registers the text to display in a tooltip. The text displays when the cursor lingers over the component.

Swing ToolTip Example

import java.awt.EventQueue;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * Class demonstrates to add tooltip.
 * @author javaguides.net
 *
 */
public class TooltipExample extends JFrame {

 private static final long serialVersionUID = 1L;

    private void initializeUI() {

     JButton btn = new JButton("Button");
        btn.setToolTipText("A button component");

        createLayout(btn);

        setTitle("Tooltip");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {

     JPanel pane = (JPanel) getContentPane();
     GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        pane.setToolTipText("Content pane");

        gl.setAutoCreateContainerGaps(true);

        gl.setHorizontalGroup(gl.createSequentialGroup()
                .addComponent(arg[0])
                .addGap(200)
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(arg[0])
                .addGap(120)
        );

        pack();
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
         TooltipExample tooltipExample = new TooltipExample();
         tooltipExample.initializeUI();
         tooltipExample.setVisible(true);
        });
    }
}
In the above example, we set a tooltip for the frame and the button. To enable a tooltip, we call the setTooltipText() method:
btn.setToolTipText("A button component");
A content pane is an instance of a JPanel component. The getContentPane() method returns a Container type. Since setting a tooltip requires a JComponent instance, we cast the object to a JPanel.
     JPanel pane = (JPanel) getContentPane();
     GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);
Note that a tooltip is set for the content pane:
pane.setToolTipText("Content pane");
We call the addGap() method for horizontal and vertical dimensions. It creates some space to the right and to the bottom of the button.
gl.setHorizontalGroup(gl.createSequentialGroup()
        .addComponent(arg[0])
        .addGap(200)
);

gl.setVerticalGroup(gl.createSequentialGroup()
        .addComponent(arg[0])
        .addGap(120)
);
The pack() method automatically sizes JFrame based on the size of its components:
pack();

Output


Comments