Java Swing | ToolTip
Last Updated :
05 Aug, 2021
We can add tooltip text to almost all the components of Java Swing by using the following method setToolTipText(String s). This method sets the tooltip of the component to the specified string s. When the cursor enters the boundary of that component a popup appears and text is displayed.
Methods used:
- getToolTipText() : returns the tooltip text for that component .
- setToolTipText(String s) : sets the tooltip text for the component .
- getToolTipText(MouseEvent e): returns the same value returned by getToolTipText(). Multi-part components such as JTabbedPane, JTable, and JTree override this method to return a string associated with the mouse event location.
- getToolTipLocation(MouseEvent e) : Returns the location (in the receiving component’s coordinate system) where the upper left corner of the component’s tool tip appears.
The following programs will illustrate the use of tooltiptext
1. Program to create a textarea and single line tool tip text to it
Java
import javax.swing.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame {
static JFrame f;
static JTextArea t1;
public static void main(String[] args)
{
f = new JFrame( "frame" );
solve s = new solve();
JPanel p = new JPanel();
t1 = new JTextArea( 20 , 20 );
t1.setToolTipText( "this is a text Area" );
p.add(t1);
f.add(p);
f.setSize( 300 , 300 );
f.show();
}
}
|
2. Program to create a text area and add multiple line tooltip text to it.
Java
import javax.swing.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame {
static JFrame f;
static JTextArea t1;
public static void main(String[] args)
{
f = new JFrame( "frame" );
solve s = new solve();
JPanel p = new JPanel();
t1 = new JTextArea( 20 , 20 );
String s1 = "<html> this is a text area <br> please add text to it <br> it has 20 rows <br> it has 20 columns </html> " ;
t1.setToolTipText(s1);
p.add(t1);
f.add(p);
f.setSize( 300 , 300 );
f.show();
}
}
|
Output:
3. program to submit name using JTextField and the tooltip text shows the previous entries.(using getToolTipText function)
Java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame implements ActionListener {
static JFrame f;
static JTextField t1;
static JButton b;
public static void main(String[] args)
{
f = new JFrame( "frame" );
solve s = new solve();
JPanel p = new JPanel();
t1 = new JTextField( 20 );
b = new JButton( "submit" );
b.addActionListener(s);
String s1 = "<html> please enter your name <br> previous entries are <br> </html>" ;
t1.setToolTipText(s1);
p.add(t1);
p.add(b);
f.add(p);
f.setSize( 300 , 300 );
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = t1.getToolTipText();
t1.setToolTipText(s.substring( 0 , s.length() - 8 ) + t1.getText() + "<br> <html" );
}
}
|
Output :
Note: the following programs might not run in an online compiler please use an online IDE.
Share your thoughts in the comments
Please Login to comment...