Let us first create a component −
JLabel label1; label1 = new JLabel("Id", SwingConstants.CENTER); Now, set the tooltip for the above component − label1.setToolTipText("Enter Id");
The following is an example to add a tooltip to a component in Java −
package my; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.Point; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Register!"); JLabel label1, label2, label3; frame.setLayout(new GridLayout(2, 2)); label1 = new JLabel("Id", SwingConstants.CENTER); label1.setToolTipText("Enter Id"); label2 = new JLabel("Age", SwingConstants.CENTER); label2.setToolTipText("Enter Age"); label3 = new JLabel("Password", SwingConstants.CENTER); label3.setToolTipText("Enter Password"); JTextField emailId = new JTextField(20); JTextField age = new JTextField(20); JPasswordField passwd = new JPasswordField(); passwd.setEchoChar('*'); frame.add(label1); frame.add(label2); frame.add(label3); frame.add(emailId); frame.add(age); frame.add(passwd); Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint(); int width = 500; int height = 200; frame.setBounds(center.x - width / 2, center.y - height / 2, width, height); frame.setVisible(true); } }
The output is as follows. On keeping mouse cursor, the tooltip text is visible −