Java/Swing JFC/Tooltip

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

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>
   
  
 
  



Changing ToolTip background color for Swing Applications

   <source lang="java">

import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.metal.MetalLookAndFeel; class MyLookAndFeel extends MetalLookAndFeel {

 protected void initSystemColorDefaults(UIDefaults table) {
   super.initSystemColorDefaults(table);
   table.put("info", new ColorUIResource(255, 255, 225));
 }

} class Main extends JFrame {

 public Main() throws Exception{
   UIManager.setLookAndFeel("MyLookAndFeel");
   setLayout(new FlowLayout());
   JButton b = new JButton();
   b.setText("<html>A
B</html>"); b.setToolTipText("<html>C
D
E</html>"); add(b); JLabel l = new JLabel("Z"); l.setToolTipText("zzzzz..."); add(l); } public static void main(String[] arg)throws Exception { Main m = new Main(); m.setVisible(true); m.setSize(new Dimension(300, 150)); m.validate(); }

}

 </source>
   
  
 
  



Colored ToolTip Example

   <source lang="java">
 

// Example from http://www.crionics.ru/products/opensource/faq/swing_ex/SwingExamples.html /* (swing1.1) */

import java.awt.Color; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; /**

* @version 1.0 12/10/98
*/

public class ColoredToolTipExample extends JFrame {

 public ColoredToolTipExample() {
   super("Colored ToolTip Example");
   UIManager.put("ToolTip.foreground", new ColorUIResource(Color.red));
   UIManager.put("ToolTip.background", new ColorUIResource(Color.yellow));
   JButton button = new JButton("Hello, world");
   button.setToolTipText("Red / Yellow");
   getContentPane().add(button);
 }
 public static void main(String args[]) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
   ColoredToolTipExample f = new ColoredToolTipExample();
   f.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   f.setSize(300, 100);
   f.show();
 }

}


 </source>
   
  
 
  



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>
   
  
 
  



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>
   
  
 
  



Html tooltips

   <source lang="java">
 

import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class HtmlToolTipDemo extends JPanel {

 public static void main(String[] a) {
   JFrame mainFrame = new JFrame();
   JLabel label = new JLabel("label");
    label.setToolTipText("<html>First line
Second Line</html>"); mainFrame.getContentPane().add(label); mainFrame.setSize(100, 100); mainFrame.setVisible(true); }

}



 </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>
   
  
 
  



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 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>
   
  
 
  



MultiLine ToolTip Example

   <source lang="java">
 

// Example from http://www.crionics.ru/products/opensource/faq/swing_ex/SwingExamples.html /* (swing1.1beta3) */

import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Enumeration; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JToolTip; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.plaf.metal.MetalToolTipUI; /**

* @version 1.0 11/09/98
*/

public class MultiLineToolTipExample extends JFrame {

 public MultiLineToolTipExample() {
   super("Multi-Line ToolTip Example");
   JButton button = new JButton("Hello, world") {
     public JToolTip createToolTip() {
       MultiLineToolTip tip = new MultiLineToolTip();
       tip.setComponent(this);
       return tip;
     }
   };
   button.setToolTipText("Hello\nworld");
   getContentPane().add(button);
 }
 public static void main(String args[]) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
   MultiLineToolTipExample f = new MultiLineToolTipExample();
   f.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   f.setSize(300, 100);
   f.show();
 }

} class MultiLineToolTip extends JToolTip {

 public MultiLineToolTip() {
   setUI(new MultiLineToolTipUI());
 }

} class MultiLineToolTipUI extends MetalToolTipUI {

 private String[] strs;
 private int maxWidth = 0;
 public void paint(Graphics g, JComponent c) {
   FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics(
       g.getFont());
   Dimension size = c.getSize();
   g.setColor(c.getBackground());
   g.fillRect(0, 0, size.width, size.height);
   g.setColor(c.getForeground());
   if (strs != null) {
     for (int i = 0; i < strs.length; i++) {
       g.drawString(strs[i], 3, (metrics.getHeight()) * (i + 1));
     }
   }
 }
 public Dimension getPreferredSize(JComponent c) {
   FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics(
       c.getFont());
   String tipText = ((JToolTip) c).getTipText();
   if (tipText == null) {
     tipText = "";
   }
   BufferedReader br = new BufferedReader(new StringReader(tipText));
   String line;
   int maxWidth = 0;
   Vector v = new Vector();
   try {
     while ((line = br.readLine()) != null) {
       int width = SwingUtilities.ruputeStringWidth(metrics, line);
       maxWidth = (maxWidth < width) ? width : maxWidth;
       v.addElement(line);
     }
   } catch (IOException ex) {
     ex.printStackTrace();
   }
   int lines = v.size();
   if (lines < 1) {
     strs = null;
     lines = 1;
   } else {
     strs = new String[lines];
     int i = 0;
     for (Enumeration e = v.elements(); e.hasMoreElements(); i++) {
       strs[i] = (String) e.nextElement();
     }
   }
   int height = metrics.getHeight() * lines;
   this.maxWidth = maxWidth;
   return new Dimension(maxWidth + 6, height + 4);
 }

}



 </source>
   
  
 
  



Set a tool tip for swing component

   <source lang="java">

import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; public class Main {

 public static void main(String[] args) {
   JFrame frame = new JFrame("Tool Tip Demo");
   frame.setSize(200, 200);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JLabel label = new JLabel("Hover on me!");
   label.setToolTipText("My JLabel Tool Tip");
   frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
   frame.getContentPane().add(label);
   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 a Tool Tip

   <source lang="java">
 

import javax.swing.JButton; import javax.swing.JComponent; public class Main {

 public static void main(String[] argv) throws Exception {
   JComponent button = new JButton("Label");
   // Set tool tip text
   button.setToolTipText("tool tip text");
 }

}


 </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 ToolTip

   <source lang="java">
 

import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JToolTip; import javax.swing.SwingUtilities; import javax.swing.plaf.metal.MetalToolTipUI; public class Main {

 public static void main(String[] argv) {
   JLabel wonLabel = new JLabel() {
     public JToolTip createToolTip() {
       return new ImageToolTip();
     }
   };
   wonLabel.setToolTipText("asdf");
 }

} class ImageToolTip extends JToolTip {

 public ImageToolTip() {
   setUI(new ImageToolTipUI());
 }

} class ImageToolTipUI extends MetalToolTipUI {

 public void paint(Graphics g, JComponent c) {
   FontMetrics metrics = c.getFontMetrics(g.getFont());
   g.setColor(c.getForeground());
   g.drawString(((JToolTip) c).getTipText(), 1, 1);
   g.drawImage(new ImageIcon("yourImage").getImage(), 1, metrics.getHeight(), c);
 }
 public Dimension getPreferredSize(JComponent c) {
   FontMetrics metrics = c.getFontMetrics(c.getFont());
   String tipText = ((JToolTip) c).getTipText();
   if (tipText == null) {
     tipText = "";
   }
   Image image = new ImageIcon("yourImage").getImage();
   int width = SwingUtilities.ruputeStringWidth(metrics, tipText);
   int height = metrics.getHeight() + image.getHeight(c);
   if (width < image.getWidth(c)) {
     width = image.getWidth(c);
   }
   return new Dimension(width, height);
 }

}


 </source>
   
  
 
  



Showing an Image in a Tool Tip with HTML

   <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>
   
  
 
  



ToolTip Location Example

   <source lang="java">
 

// Example from http://www.crionics.ru/products/opensource/faq/swing_ex/SwingExamples.html /* (swing1.1.1) */

import java.awt.Container; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager;

/**

* @version 1.0 08/27/98
*/

public class ToolTipLocationExample extends JFrame {

 public ToolTipLocationExample() {
   super("ToolTip Location Example");
   // above position
   JButton buttonAbove = new JButton("Above") {
     public Point getToolTipLocation(MouseEvent e) {
       return new Point(20, -30);
     }
   };
   buttonAbove.setToolTipText("Hello world");
   // blow (default) position
   JButton buttonBelow = new JButton("Below");
   buttonBelow.setToolTipText("Hello world");
   // whatever
   final RelocatableToolTipButton buttonRelocate = new RelocatableToolTipButton(
       "Relocate");
   buttonRelocate.setToolTipText("Hello world");
   buttonRelocate.addActionListener(new ActionListener() {
     JPanel messagePanel = createPanel();
     JTextField locationX, locationY;
     public void actionPerformed(ActionEvent e) {
       Point p = buttonRelocate.getToolTipLocation(null);
       if (p == null) {
         locationX.setText("default");
         locationY.setText("default");
       } else {
         locationX.setText(Integer.toString(p.x));
         locationY.setText(Integer.toString(p.y));
       }
       int result = JOptionPane.showOptionDialog(
           ToolTipLocationExample.this, messagePanel, "Location",
           JOptionPane.OK_CANCEL_OPTION,
           JOptionPane.QUESTION_MESSAGE, null, null, null);
       if (result == JOptionPane.OK_OPTION) {
         try {
           int x = Integer.parseInt(locationX.getText());
           int y = Integer.parseInt(locationY.getText());
           buttonRelocate.setToolTipLocation(new Point(x, y));
         } catch (NumberFormatException ex) {
           ex.printStackTrace();
         }
       }
     }
     private JPanel createPanel() {
       JPanel p = new JPanel();
       p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
       p.add(new JLabel("  X: "));
       p.add(locationX = new JTextField());
       p.add(new JLabel("  Y: "));
       p.add(locationY = new JTextField());
       return p;
     }
   });
   JPanel panel = new JPanel();
   panel.add(buttonAbove);
   panel.add(buttonBelow);
   panel.add(buttonRelocate);
   Container c = getContentPane();
   c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
   c.add(Box.createVerticalStrut(30));
   c.add(panel);
 }
 class RelocatableToolTipButton extends JButton {
   Point toolTipLocation;
   RelocatableToolTipButton(String label) {
     super(label);
     toolTipLocation = null;
   }
   public Point getToolTipLocation(MouseEvent e) {
     return toolTipLocation;
   }
   public void setToolTipLocation(Point location) {
     toolTipLocation = location;
   }
 }
 public static void main(String args[]) {
   try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
   } catch (Exception evt) {}
 
 
   ToolTipLocationExample frame = new ToolTipLocationExample();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   frame.setSize(300, 130);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Tooltip Sample

   <source lang="java">
 

import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JToolTip; public class TooltipSample {

 public static void main(String args[]) {
   String title = "Tooltip Sample";
   JFrame frame = new JFrame(title);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container container = frame.getContentPane();
   JPanel panel = new JPanel();
   panel.setToolTipText("<HtMl>Tooltip
Message"); container.add(panel, BorderLayout.CENTER); JButton button = new JButton("Hello World") { public JToolTip createToolTip() { JToolTip tip = super.createToolTip(); tip.setBackground(Color.yellow); tip.setForeground(Color.green); return tip; } public boolean contains(int x, int y) { if (x < 100) { setToolTipText("Got Green Eggs?"); } else { setToolTipText("Got Ham?"); } return super.contains(x, y); } }; button.setToolTipText("Hello World"); frame.getContentPane().add(button, BorderLayout.NORTH); frame.setSize(300, 150); 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>
   
  
 
  



Working with Tooltip Text

   <source lang="java">
 

import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JButton; import javax.swing.JFrame; public class ButtonTipTest {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Tool Tips");
   Container contentPane = frame.getContentPane();
   JButton b = new JButton("Button");
   b.setToolTipText("Go Away");
   contentPane.add(b, BorderLayout.NORTH);
   frame.setSize(300, 200);
   frame.show();
 }

}


 </source>