Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to use and set ToolTip for Swing components in Java ?.

Program to demonstrate how to use and set ToolTip for Swing components in Java

package com.hubberspot.example;

import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ToolTipDemo {

 public static void main(String[] args) {

  // 1. Create a simple frame by creating an object 
  // of JFrame. 
  JFrame frame = new JFrame();

  // 2. Give the frame a title "Tool Tip Frame" by calling 
  // setTitle method on frame object
  frame.setTitle("Tool Tip Frame");

  // 3. Give frame a size in pixels as say 300,300 
  frame.setSize(300, 300);

  // 4. set a operation when a user close the frame, here it 
  // closes the frame and exits the application

  // 5. Create a button by creating an Object of class 
  // JButton. 
  JButton button = new JButton();

  // 6. set the text of button as "Button"

  // 7. Create a label by creating an Object of class 
  // JLabel
  JLabel label = new JLabel();

  // 8. set the text of label as "Label"

  // 9. In order to create a tool tip for label, 
  // button or any swing components, we call setToolTipText
  // method and passing it the information we want to display 
  // when user hovers over the swing components
  button.setToolTipText("Tool Tip for Button");
  label.setToolTipText("Tool Tip for Label");

  // 10. for adding all these swing components to frame
  // we first get the content pane which returns a 
  // Container
  Container container = frame.getContentPane();

  // 11. We create a Layout for Swing Components
  // here we are using FlowLayout with value as "center'
  // it will make the swing components float to center
  FlowLayout layout = new FlowLayout(FlowLayout.CENTER);

  // 12. We set the layout for container

  // 13. We add the button and label to it

  // 14. after adding button and label, we make it 
  // visible on the frame by calling the method as 
  // setVisible and passing value as true.


Output of the program :


© 2021 Learn Java by Examples Template by Hubberspot