Java JMenuItem add tooltip

Description

Java JMenuItem add tooltip

JMenuItem jmiSave = new JMenuItem("Save");
jmiSave.setToolTipText("Save the MenuDemo program.");
      

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

public class Main implements ActionListener {
   public Main() {
      // Create a new JFrame container.
      JFrame jfrm = new JFrame("Menu Demo");

      // Specify FlowLayout for the layout manager.
      jfrm.setLayout(new FlowLayout());

      // Give the frame an initial size.
      jfrm.setSize(220, 200);// w  w  w  .j a  va2s. c  om

      // Terminate the program when the user closes the application.
      jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Create the menu bar.
      JMenuBar jmb = new JMenuBar();

      // Create the File menu.
      JMenu jmFile = new JMenu("File");
      jmFile.setMnemonic(KeyEvent.VK_F);

      JMenuItem jmiOpen = new JMenuItem("Open");

      JMenuItem jmiClose = new JMenuItem("Close", KeyEvent.VK_C);

      JMenuItem jmiSave = new JMenuItem("Save");
      jmiSave.setToolTipText("Save the MenuDemo program.");
      
      JMenuItem jmiExit = new JMenuItem("Exit");
      jmFile.add(jmiOpen);
      jmFile.add(jmiClose);
      jmFile.add(jmiSave);
      jmFile.addSeparator();
      jmFile.add(jmiExit);
      jmb.add(jmFile);

      // Create the Help menu.
      JMenu jmHelp = new JMenu("Help");
      JMenuItem jmiAbout = new JMenuItem("About");
      jmHelp.add(jmiAbout);
      jmb.add(jmHelp);

      // Add action listeners for the menu items.
      jmiOpen.addActionListener(this);
      jmiClose.addActionListener(this);
      jmiSave.addActionListener(this);
      jmiExit.addActionListener(this);
      jmiAbout.addActionListener(this);

      // Add the menu bar to the frame.
      jfrm.setJMenuBar(jmb);

      // Display the frame.
      jfrm.setVisible(true);
   }

   // Handle menu item action events.
   public void actionPerformed(ActionEvent ae) {
      // Get the action command from the menu selection.
      String comStr = ae.getActionCommand();

      // If user chooses Exit, then exit the program.
      if (comStr.equals("Exit"))
         System.exit(0);

      // Otherwise, display the selection.
      System.out.println(comStr + " Selected");
   }

   public static void main(String args[]) {
      // Create the frame on the event dispatching thread.
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            new Main();
         }
      });
   }
}



PreviousNext

Related