How to set tooltip text for JCheckBox in Java?

Java 8Object Oriented ProgrammingProgramming

For JCheckBox, use the following to set tooltip text:

checkBox1.setToolTipText("Sports Football");
checkBox2.setToolTipText("Sports Tennis");

Tooltip text is visible whenever you will place cursor on that particular text.

The following is an example. Here, we have set the tooltip text for both the sports:

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   public SwingDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingDemo swingControlDemo = new SwingDemo();
      swingControlDemo.showCheckBoxDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing");
      mainFrame.setSize(600,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }
      });
      headerLabel = new JLabel("", JLabel.CENTER);
      statusLabel = new JLabel("",JLabel.CENTER);
      statusLabel.setSize(350,100);
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());
      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);
   }
   private void showCheckBoxDemo(){
      headerLabel.setText("Favourite Sports");
      final JCheckBox checkBox1 = new JCheckBox("Football");
      final JCheckBox checkBox2 = new JCheckBox("Tennis");
      checkBox1.setToolTipText("Sports Football");
      checkBox2.setToolTipText("Sports Tennis");
      checkBox1.setMnemonic(KeyEvent.VK_F);
      checkBox2.setMnemonic(KeyEvent.VK_T);
      checkBox1.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Football Checkbox: " + (e.getStateChange()==1?"checked":"unchecked"));
         }
      });
      checkBox2.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Tennis Checkbox: "+ (e.getStateChange()==1?"checked":"unchecked"));
         }
      });
      controlPanel.add(checkBox1);
      controlPanel.add(checkBox2);
      mainFrame.setVisible(true);
   }
}

The output is as follows. Here, you can see on mouse hover the tooltip is visible:

Output

raja
Published on 06-May-2019 08:12:29
Advertisements