简体   繁体   English

Java-如何为JFrame设置setToolTipText

[英]Java- How to set setToolTipText for JFrame

I would like to move the mouse over an image which was plotted on a JFrame using g2D.drawRenderedImag and display the x, y of that pixel at the tooltip text right next to mouse cursor. 我想将鼠标移到使用g2D.drawRenderedImag在JFrame上绘制的图像上,并在鼠标光标旁边的工具提示文本处显示该像素的x,y。 ie: 即:

Graphics2D g2D = (Graphics2D)g;
g2D.drawRenderedImage...

I know how to read the x,y but don't know how to set setToolTipText for a JFrame. 我知道如何读取x,y,但不知道如何为JFrame设置setToolTipText。 Can you guys help me please? 你们能帮我吗? I mean I can not do like this JFrame.setToolTipText !!!! 我的意思是我不能喜欢这个JFrame.setToolTipText !!!!

you can do componentName.setToolTipText("context"); 您可以执行componentName.setToolTipText(“ context”); for more information, you can check http://docs.oracle.com/javase/tutorial/uiswing/components/tooltip.html lots of useful information about the Swing API 有关更多信息,您可以查看http://docs.oracle.com/javase/tutorial/uiswing/components/tooltip.html有关Swing API的许多有用信息

I see now you want to do it for a JFrame not a component, this works for a JFrame's title, maybe it helps 我现在看到您想要为JFrame而不是组件执行此操作,这适用于JFrame的标题,也许有帮助

 import darrylbu.util.SwingUtils;
import javax.swing.*;

public class FrameTitleToolTip {

   public static void main(String[] args) {
      JFrame.setDefaultLookAndFeelDecorated(true);
      SwingUtilities.invokeLater(new Runnable() {

         @Override
         public void run() {
            new FrameTitleToolTip().makeUI();
         }
      });
   }

   public void makeUI() {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(400, 400);
      for (JComponent component : SwingUtils.getDescendantsOfType(JComponent.class,
            frame)) {
         if (component.getClass().getName().contains("MetalTitlePane")) {
            component.setToolTipText("Tooltip for frame title bar");
            break;
         }
      }
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}

You need to take advantage of the getToolTip methods provided by JComponent 您需要利用JComponent提供的getToolTip方法

You will also need to register with the ToolTipManager , either by calling setToolTipText on your component with a non null value, or using ToolTipManager#registerComponent 您还需要与注册ToolTipManager ,通过调用setToolTipText您的组件与一个非null值,或者使用的ToolTipManager#registerComponent

Updated with example 更新了示例

You seem to be saying that you're rendering directly to a JFrame , presumably by overriding the paint method. 您似乎在说要直接渲染到JFrame ,大概是通过重写paint方法。 This is highly unrecommended, apart from anything, top level containers aren't double buffered, so you're going to end up with the possibility of flickering when you update the screen contents. 强烈建议不要这样做,除了任何东西,顶级容器都不是双缓冲的,因此在更新屏幕内容时最终会出现闪烁的可能性。

Much better to use something like JPanel , which is double buffered AND has the benefit of doing the work for you (when it comes to something like displaying tool tips). 最好使用JPanel东西,它是双缓冲的,并且具有为您完成工作的好处(涉及显示工具提示之类的东西)。 It also makes your component more portable and re-usable 这也使您的组件更加便携和可重复使用

在此处输入图片说明

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestToolTipImage {

    public static void main(String[] args) {
        new TestToolTipImage();
    }

    public TestToolTipImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage img;

        public ImagePane() {
            try {
                img = ImageIO.read(getClass().getResource("/TestToolTipImage.jpg"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            ToolTipManager.sharedInstance().registerComponent(this);
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
        }

        @Override
        public String getToolTipText(MouseEvent event) {

            String text = super.getToolTipText(event);

            if (img != null) {

                int xOffset = (getWidth() - img.getWidth()) / 2;
                int yOffset = (getHeight() - img.getHeight()) / 2;
                Rectangle bounds = new Rectangle(xOffset, yOffset, img.getWidth(), img.getHeight());

                if (bounds.contains(event.getPoint())) {

                    int x = event.getPoint().x - xOffset;
                    int y = event.getPoint().y - yOffset;
                    int rgb = img.getRGB(x, y);                    
                    String hex = Integer.toHexString(rgb & 0xffffff);

                    StringBuilder sb = new StringBuilder(128);
                    sb.append("<html><table><tr><td>Pixel at ").
                                    append(x).append("x").append(y).
                                    append("</td>");
                    sb.append("<td bgcolor='#").append(hex).append("'>&nbsp;</td>");
                    sb.append("</tr></table><html>");

                    System.out.println(sb.toString());
                    text = sb.toString();

                }

            }

            return text;

        }

        @Override
        public Point getToolTipLocation(MouseEvent event) {
            return event.getPoint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                int x = (getWidth() - img.getWidth()) / 2;
                int y = (getHeight() - img.getHeight()) / 2;
                g.drawImage(img, x, y, this);
            }
        }
    }
}

Since JFrame doesn't inherit from JComponent , it doesn't have setToolTipText method. 由于JFrame不继承自JComponent ,所以它没有setToolTipText方法。 Try getting JLayeredPan e from JFrame and invoke it's tooltip method: 尝试从JFrame获取JLayeredPan e并调用其工具提示方法:

getLayeredPane().setToolTipText("text");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM