Java Tutorial/Swing/JToolTip

Материал из Java эксперт
Перейти к: навигация, поиск

Adding JToolTip to component

Tooltip text is normally one line long.

Calling the public void setToolTipText(String text) method from JComponent to create a tooltip.



   <source lang="java">

import javax.swing.JButton; import javax.swing.JFrame; public class ToolTipDemo {

 public static void main(String args[]) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JButton b = new JButton("Hello, World");
   frame.add(b,"Center");
   b.setToolTipText("asdf");
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





By default, the lines are left justified. Center the lines.

   <source lang="java">

import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
component.setToolTipText("<html>
" + "This is a" + "
" + "tool tip" + "
</html>");
 }

}</source>





Creating Customized JToolTip Objects: customize and override its inherited public JToolTip createToolTip()

   <source lang="java">

import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JToolTip; public class ToolTipBackgroundForeground {

 public static void main(String args[]) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JButton b = new JButton("Hello, World") {
     public JToolTip createToolTip() {
       JToolTip tip = super.createToolTip();
       tip.setBackground(Color.YELLOW);
       tip.setForeground(Color.RED);
       return tip;
     }
   };
   frame.add(b,"Center");
   b.setToolTipText("asdf");
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





Creating HTML 3.2 formatted text tooltip: the text string begins with "html" in any case

   <source lang="java">

import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JToolTip; public class ToolTipHTML {

 public static void main(String args[]) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JButton b = new JButton("Hello, World");
   frame.add(b,"Center");
   b.setToolTipText("<html>asdfbold</html>");
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





Customizing a JToolTip Look and Feel

Property StringObject TypeToolTip.backgroundColorToolTip.backgroundInactiveColorToolTip.borderBorderToolTip.borderInactiveColorToolTip.fontFontToolTip.foregroundColorToolTip.foregroundInactiveColorToolTip.hideAcceleratorBooleanToolTipUIString


Disable / enable application tool tips

   <source lang="java">

import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.ToolTipManager; public class Main extends JFrame {

 public Main() throws HeadlessException {
   setSize(300, 300);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
   JButton disable = new JButton("DISABLE");
   disable.setToolTipText("disabled.");
   disable.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       ToolTipManager.sharedInstance().setEnabled(false);
     }
   });
   JButton enable = new JButton("ENABLE");
   enable.setToolTipText("enabled.");
   enable.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       ToolTipManager.sharedInstance().setEnabled(true);
     }
   });
   getContentPane().add(enable);
   getContentPane().add(disable);
 }
 public static void main(String[] args) {
   new Main().setVisible(true);
 }

}</source>





Displaying Mnemonics in tooltip text

   <source lang="java">

import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JFrame; public class MnemonicButton {

 public static void main(String args[]) {
   JFrame frame = new JFrame("DefaultButton");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JButton button1 = new JButton("Text Button");
   button1.setMnemonic(KeyEvent.VK_B);
   frame.add(button1);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





Displaying Positional Tooltip Text: display different tooltip depending on the mouse pointer"s location

   <source lang="java">

import javax.swing.JButton; import javax.swing.JFrame; public class DisplayingPositionalTooltip {

 public static void main(String args[]) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JButton button = new JButton("Hello, World") {
     public boolean contains(int x, int y) {
       if (x < 50) {
         setToolTipText("AAAAAAAAA");
       } else {
         setToolTipText("BBBBBBBBBBBBBB");
       }
       return super.contains(x, y);
     }
   };
   frame.add(button, "Center");
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





Enabling and Disabling Tool Tips

   <source lang="java">

import javax.swing.ToolTipManager; public class Main {

 public static void main(String[] argv) throws Exception {
   // Enable tool tips for the entire application
   ToolTipManager.sharedInstance().setEnabled(true);
   // Disable tool tips for the entire application
   ToolTipManager.sharedInstance().setEnabled(false);
 }

}</source>





Italicize the second line

   <source lang="java">

import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
   component.setToolTipText("<html>" + "This is a" + "
" + "tool tip" + "</html>"); }

}</source>





Label with tooltip

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.GridLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; /*

* LabelDemo.java needs one other file: images/middle.gif
*/

public class LabelDemo extends JPanel {

 public LabelDemo() {
   super(new GridLayout(3, 1)); // 3 rows, 1 column
   JLabel label1, label2, label3;
   ImageIcon icon = createImageIcon("images/middle.gif",
       "a pretty but meaningless splat");
   // Create the first label.
   label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
   // Set the position of its text, relative to its icon:
   label1.setVerticalTextPosition(JLabel.BOTTOM);
   label1.setHorizontalTextPosition(JLabel.CENTER);
   // Create the other labels.
   label2 = new JLabel("Text-Only Label");
   label3 = new JLabel(icon);
   // Create tool tips, for the heck of it.
   label1.setToolTipText("A label containing both image and text");
   label2.setToolTipText("A label containing only text");
   label3.setToolTipText("A label containing only an image");
   // Add the labels.
   add(label1);
   add(label2);
   add(label3);
 }
 /** Returns an ImageIcon, or null if the path was invalid. */
 protected static ImageIcon createImageIcon(String path, String description) {
   java.net.URL imgURL = LabelDemo.class.getResource(path);
   if (imgURL != null) {
     return new ImageIcon(imgURL, description);
   } else {
     System.err.println("Couldn"t find file: " + path);
     return null;
   }
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event dispatch thread.
  */
 private static void createAndShowGUI() {
   // Create and set up the window.
   JFrame frame = new JFrame("LabelDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // Add content to the window.
   frame.add(new LabelDemo());
   // Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   // Schedule a job for the event dispatch thread:
   // creating and showing this application"s GUI.
   SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       // Turn off metal"s use of bold fonts
       UIManager.put("swing.boldMetal", Boolean.FALSE);
       createAndShowGUI();
     }
   });
 }

}</source>





Make a tool tips appear immediately

   <source lang="java">

import javax.swing.ToolTipManager; public class Main {

 public static void main(String[] argv) throws Exception {
   // Get current delay
   int initialDelay = ToolTipManager.sharedInstance().getInitialDelay();
   // Show tool tips immediately
   ToolTipManager.sharedInstance().setInitialDelay(0);
   // Show tool tips after a second
   initialDelay = 1000;
   ToolTipManager.sharedInstance().setInitialDelay(initialDelay);
 }

}</source>





Making Tool Tips Remain Visible

   <source lang="java">

import javax.swing.ToolTipManager; public class Main {

 public static void main(String[] argv) throws Exception {
   // Get current delay
   int dismissDelay = ToolTipManager.sharedInstance().getDismissDelay();
   // Keep the tool tip showing
   dismissDelay = Integer.MAX_VALUE;
   ToolTipManager.sharedInstance().setDismissDelay(dismissDelay);
 }

}</source>





Modify the behaviour of the default JToolTip

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JToolTip; public class Main {

 public static void main(String args[]) {
   JFrame frame = new JFrame("JToolTip Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JButton b1 = new JButton("Button 1") {
     public JToolTip createToolTip() {
       JToolTip tip = super.createToolTip();
       tip.setForeground(Color.YELLOW);
       return tip;
     }
     public Point getToolTipLocation(MouseEvent event) {
       return new Point((event.getX() + 100), (event.getY() + 100));
     }
   };
   b1.setToolTipText("HELLO");
   frame.add(b1, BorderLayout.NORTH);
   frame.setSize(300, 150);
   frame.setVisible(true);
 }

}</source>





Set the location of the tool tip such that its nw corner coincides with the bottom center of the button

   <source lang="java">

import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton button = new JButton("My Button") {
     public Point getToolTipLocation(MouseEvent event) {
       return new Point(getWidth() / 2, getHeight());
     }
   };
 }

}</source>





Setting the Location of a Tool Tip

   <source lang="java">

import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton button = new JButton("My Button") {
     public Point getToolTipLocation(MouseEvent event) {
       return new Point(0, 0);
     }
   };
 }

}</source>





Showing an Image in a Tool Tip

   <source lang="java">

import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
   String imageName = "file:image.jpg";
   component.setToolTipText("<html>Here is an image <img src=" + imageName + "></html>");
 }

}</source>





Showing Multiple Lines in a Tool Tip

   <source lang="java">

import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
   component.setToolTipText("<html>" + "This is a" + "
" + "tool tip" + "</html>"); }

}</source>





Use images in tooltips

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JLabel; public class Main {

 public static void main(String[] args) {
   JFrame frame = new JFrame();
   JLabel label = new JLabel("Label with image in Tooltip!");
   label.setToolTipText("<html><img src=\"" + Main.class.getResource("tooltip.gif")
       + "\"> Tooltip ");
   label.setHorizontalAlignment(JLabel.CENTER);
   frame.setContentPane(label);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setBounds(100, 100, 200, 100);
   frame.setVisible(true);
 }

}</source>





Use the default tool tip location

   <source lang="java">

import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton button = new JButton("My Button") {
     public Point getToolTipLocation(MouseEvent event) {
       return null;
     }
   };
   // Set the tool tip text
   button.setToolTipText("aString");
 }

}</source>