`
wuce7758
  • 浏览: 177515 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
  • YTT1121: 有网络拓扑发现的源代码么?能不能发我一份学习一下,现在我正要做 ...
    java拓扑图
  • YTT1121: 大神,有网络拓扑发现的源代码么?或者您会编写么?我需要做科研改 ...
    java拓扑图
  • YTT1121: 大神,有网络拓扑发现的源代码么?或者您会编写么?我需要做科研改 ...
    java拓扑图
  • poettang: 求代码分享学习,谢谢!膜拜大神!258026921@qq.co ...
    java拓扑图
  • oiqio: 87836238@qq.com,感谢楼主,来一份~
    java拓扑图

在自定义 JToolTip 里面显示组件

阅读更多

在自定义 JToolTip 里面显示组件

JToolTip

我们经常可以看到很多 Windows 程序显示出各种各样好看的工具栏提示, 不是默认的那种只有文字的提示... 但是 Java Swing 默认的那个, 似乎只有那个一行文字, well, how can we change it? 请参阅: JFC -- Chapter 24 - Building a Custom Component http://mail.phys-iasi.ro/Library/Computing/jfc_unleashed/ch24.htm

笔者基于文中的介绍写出了自己的解决方案. First, 写一个自定义的 ToolTipUI 来显示 JToolTip, 实现下列逻辑:
1. 如果没有在 JToolTip 中包含子组件(还记得嘛, 所有 JComponent 都是容器), 那么按照普通的模式显示 JToolTip, 稍微改进了一点, 就是可以显示多行的文字, 例如 "a\nb" 这样的文字就被显示为两行, 而不是默认的 JToolTip 显示的单行文本.
2. 如果包含了子组件, 就忽略设置的提示文本, 转而显示里面包含的组件, 这样就实现了在 JToolTip 中显示组件的功能. 源代码如下:

import java.awt.*;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicToolTipUI;
/**
 * The ComponentToolTipUI class may be registered with the UIManager
 * to replace the ToolTipUI for JToolTip instances. When used, it
 * divides the ToolTip into multiple lines, if has child components,
 * all child components will be displayed instead of only some tooltip
 * text. Each line is divided by
 * the '\ n' character.
 * <p>
 * @author Mike Foley
 **/
public class ComponentToolTipUI extends BasicToolTipUI
{
    /**
     * The single shared UI instance.
     **/
    static ComponentToolTipUI sharedInstance = new ComponentToolTipUI();
    /**
     * The margin around the text.
     **/
    static final int MARGIN = 2;
    /**
     * The character to use in the StringTokenizer to
     * separate lines in the ToolTip. This could be the
     * system property end of line character.
     **/
    static final String lineSeparator = "\n";
    /**
     * MultiLineToolTipUI, constructor.
     * <p>
     * Have the constructor be protected so we can be subclassed,
     * but not created by client classes.
     **/
    protected ComponentToolTipUI()
    {
        super();
    }
    /**
     * Create the UI component for the given component.
     * The same UI can be shared for all components, so
     * return our shared instance.
     * <p>
     * @param c The component to create the UI for.
     * @return Our shared UI component instance.
     **/
    public static ComponentUI createUI(JComponent c)
    {
        return sharedInstance;
    }
    /**
     * Paint the ToolTip. Use the current font and colors
     * set for the given component.
     * <p>
     * @param g The graphics to paint with.
     * @param c The component to paint.
     **/
    public void paint(Graphics g, JComponent c)
    {
  // Paints each of the components in this container.
  if(c.getComponentCount() > 0) {
          c.paintComponents(g);
          return;
  }
  // If no components, then paint a muiltiple line tooltip


  //
        // Determine the size for each row.
        //
        Font font = c.getFont();
        FontMetrics fontMetrics = c.getFontMetrics(font);
        int fontHeight = fontMetrics.getHeight();
        int fontAscent = fontMetrics.getAscent();
        //
        // Paint the background in the tip color.
        //
        g.setColor(c.getBackground());
        Dimension size = c.getSize();
        g.fillRect(0, 0, size.width, size.height);
        //
        // Paint each line in the tip using the
        // foreground color. Use a StringTokenizer
        // to parse the ToolTip. Each line is left
        // justified, and the y coordinate is updated
        // through the loop.
        //
        g.setColor(c.getForeground());
        int y = 2+fontAscent;
        String tipText = ((JToolTip)c).getTipText();
        StringTokenizer tokenizer = new StringTokenizer(tipText, lineSeparator);
        int numberOfLines = tokenizer.countTokens();
        for (int i = 0; i < numberOfLines; i++)
        {
            g.drawString(tokenizer.nextToken(), MARGIN, y);
            y += fontHeight;
        }
    }

    // paint
    /**
     * The preferred size for the ToolTip is the width of
     * the longest row in the tip, and the height of a
     * single row times the number of rows in the tip.
     *
     * @param c The component whose size is needed.
     * @return The preferred size for the component.
     **/
    public Dimension getPreferredSize(JComponent c)
    {
        // If has children components
  if(c.getComponentCount() > 0) {
         return c.getLayout().preferredLayoutSize(c);
  }

  //
        // Determine the size for each row.
        //
        Font font = c.getFont();
        FontMetrics fontMetrics = c.getFontMetrics(font);
        int fontHeight = fontMetrics.getHeight();
        //
        // Get the tip text string.
        //
        String tipText = ((JToolTip)c).getTipText();
        //
        // Empty tip, use a default size.
        //
        if (tipText == null)
            return new Dimension(2 * MARGIN, 2 * MARGIN);
        //
        // Create a StringTokenizer to parse the ToolTip.
        //
        StringTokenizer tokenizer = new StringTokenizer(tipText, lineSeparator);
        int numberOfLines = tokenizer.countTokens();
        //
        // Height is number of lines times height of a single line.
        //
        int height = numberOfLines * fontHeight;
        //
        // Width is width of longest single line.
        //
        int width = 0;
        for (int i = 0; i < numberOfLines; i++)
        {
            int thisWidth = fontMetrics.stringWidth(tokenizer.nextToken());
            width = Math.max(width, thisWidth);
        }
        //
        // Add the margin to the size, and return.
        //
        return (new Dimension(width + 2 * MARGIN, height + 2 * MARGIN));

    }
    // getPreferredSize
}

// ComponentToolTipUI

接着, 我们定义一个包含了其它组件的 JToolTip:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyTooltip extends javax.swing.JToolTip
{
  JButton jButton1 = new JButton();
  FlowLayout flowLayout1 = new FlowLayout();
  JTextField jTextField1 = new JTextField();

 public MyTooltip()
    {
    try  {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
 }

 public void setTipText(String tipText) {
    super.setTipText(tipText);
//    button.setText(tipText);
 }

 

  private void jbInit() throws Exception {
//    jLabel1.setMaximumSize(new Dimension(400, 300));
//    jLabel1.setMinimumSize(new Dimension(400, 300));
//    jLabel1.setPreferredSize(new Dimension(400, 300));
    jButton1.setText("This is a button included in the tool tip.");
    this.setLayout(flowLayout1);
    this.setOpaque(true);
    jTextField1.setText("jTextField1");
    this.add(jButton1, null);
    this.add(jTextField1, null);
  }


}

最后, 我们编写一个测试类来测试这个 JToolTip:

import java.awt.event.*;
import javax.swing.*;

public class MyButton extends javax.swing.JButton
{

 public MyButton()
    {
 }

 public JToolTip createToolTip() {
  JToolTip tip = new MyTooltip();
  tip.setComponent(this);
  tip.setTipText(getToolTipText());
  return tip;
 }

 public static void main(String[] args)
    {
  try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  } catch (Exception ex) {
    ex.printStackTrace();
  }

        try
        {
            String multiLineToolTipUIClassName =
            "ComponentToolTipUI";

//            System.out.println(multiLineToolTipUIClassName);

            UIManager.put( "ToolTipUI", multiLineToolTipUIClassName );
            UIManager.put( multiLineToolTipUIClassName,
            Class.forName( multiLineToolTipUIClassName ) );
        }
        catch( ClassNotFoundException cnfe )
        {
            System.err.println( "MultiLine ToolTip UI class not found" );
            System.err.println( cnfe );
        }

  final JFrame frame = new JFrame("Test JToolTip");
  frame.addWindowListener(new java.awt.event.WindowAdapter() {
         public void windowClosing(WindowEvent e) {
    frame.dispose();
    System.exit(0);
   }
  });

  MyButton button = new MyButton();
  button.setText("这个按钮显示一个包含组件的工具提示");
  button.setToolTipText("提示");

  frame.getContentPane().add(button);

  JButton buttonPlain = new JButton("这是一个包含多行文本提示的普通按钮");
  buttonPlain.setToolTipText("Line 1\nLine 2\n");

  frame.getContentPane().add(java.awt.BorderLayout.SOUTH, buttonPlain);

//  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.pack();
  frame.show();
 }


}

编译并运行最后一个类: MyButton, 就可以看到包含了可以交互的按钮和文本框, 以及一个显示两行文本的工具栏提示。

分享到:
评论

相关推荐

    java swing-JToolTip的使用

    JToolTip 是 Java Swing 库提供的一个工具提示组件,用于在鼠标悬停或其他交互事件发生时显示文本提示信息。

    Java Swing实例源码包.rar

    Java Swing实例源码包,包括了JComboBox 、Border、JList、JMenu、JSlider、JTabbedPane、JTable、JToolTip、JTree等常用Swing组件的用法示例,对Java编写界面来说,Swing确实是个不错的选择,希望这些示例能让你更...

    SWING样例

    SUN官方出的有关swing设计的样例,其中包括JTable的34个例子、JList的15个例子、JToolTip的4个例子、JComboBox的5个例子、JComboBox的6个例子、Border的3个例子、JSlider的4个例子。 都含源码,需要自己编译。

    node-v10.17.0-linux-x64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    使用opencv决策树训练mushroom数据集-python源码.zip

    使用opencv决策树训练mushroom数据集-python源码.zip

    基于Faster RCNN的人脸检测识别系统python源码+项目说明+wider-face数据集.zip

    基于Faster RCNN的人脸检测识别系统python源码+项目说明+wider_face数据集.zip ### 三,使用说明 1. 锚框的大小为[128、256、512],比率为[1:1、1:2、2:1]。 2. tensorflow的版本是'1.9.0',keras的版本是'2.1.5',除了使用tensorflow2.0之后版本,其他版本都可以尝试。不支持python2.x。 3. 使用的是tensorflow backend,theano可以自行修改。 4. wider face的Label文件格式与VOC2012的label不同,而我使用的Faster RCNN需要VOC2012的格式,所以需要将label文件转换一下格式。具体可以查看 [https://blog.csdn.net/qq_37431083/article/details/102742322](https://blog.csdn.net/qq_37431083/article/details/102742322) 5. 在训练过程中可能会出现`"ValueError: 'a' cannot be empty

    1985-2022年广东省企业专利明细数据-专利名称专利类型专利摘要专利授权专利分类号等

    1985-2022年广东省企业专利明细数据-专利名称专利类型专利摘要专利授权专利 分类号等 1、数据说明: 在知识经济时代,技术创新是实现经济内生增长的关键动力, 科技优势成为经济竞争优势的根本源泉。新一轮科技革命和产业变革加速,全球创新速度加 快,我国正在经历发展方式转变、经济结构优化、新旧动能转换的攻关期,创新日益成为破 解发展难题的关键。专利作为技术与知识的载体,其申请数量是创新研究中衡量创新最常用 的指标之一,中国成为创新领先国家也同样体现在专利申请量上。改革开放 40 年来, 我们的知识产权事业取得了举世瞩目的巨大成功,但也面临着“大而不强”的问题。引导专 利从追求数量向提高质量转变,这是国家近几年的政策扶持重点,也是未来专利申请审查的 一个风向标,针对海量专利数据的价值识别与预测,逐渐成为当前的研究热点。 本数据提 供了1985-2022年广东省的企业专利明细数据,可用于各类专利相关研究。 2、 数据来源: 数据来源为国家知识产权局,利用知识产权局的高级检索,选择地区、年份、 专利类型,对全国31省的各类专利进行统计并将检索结果整理为面板数据,包括发明公开 、发明授权、实用

    Kaggle竞赛 稻田病害分类-python源码.zip

    Kaggle竞赛 稻田病害分类-python源码.zip

    基于paddle+mediapipe注意力机制的表情识别python源码+数据集+模型+项目说明.zip

    文件目录解释 # 1. Models 用来存放的模型,可以是已有的Paddle格式的模型 # 2. Pages - assets 用到的图片资源 - assets.qrc 使用PySide生成的样式文件 - assets_rc.py GUI界面的样式文件,此目录和根目录都有,我忘记是调用的哪一个了,所以都保留了。 # 3. Utils - AttResNet.py 网络代码 - DatasetProcess.py 数据集处理代码 - FaceDetection.py 人脸检测代码 - Predict.py 模型预测代码 - VisualTrain.py 模型训练代码 - CSV文件 用来保存数据集和创建的信息 # 4. Dataset 存放数据集的目录 注意事项 * # 配置好环境,安装使用PySide的工具,不会安装见如下以PyCharm为例的说明 1. 依次点击 File:arrow_right:Settings:arrow_right:Tools:arrow_right:External Tools:arrow_right::heavy_plus_sign:添加PySide工具,

    机械设计小线圈生产打蜡机sw20非常好的设计图纸100%好用.zip

    机械设计小线圈生产打蜡机sw20非常好的设计图纸100%好用.zip

    手机和讯财金网触屏版自适应手机wap财金网站模板.zip

    触屏版自适应手机wap软件网站模板 触屏版自适应手机wap软件网站模板

    基于普中51开发板的超声波测距+蜂鸣器报警 (附开发板原理图)

    基于普中51开发板的超声波测距+蜂鸣器报警 (附开发板原理图) 基于普中51开发板的超声波测距+蜂鸣器报警 (附开发板原理图)

    机械设计大倾角输送机sw17非常好的设计图纸100%好用.zip

    机械设计大倾角输送机sw17非常好的设计图纸100%好用.zip

    1999-2022年投资者信心指数表、消费者信心指数表、企业景气指数表、企业家信心指数表

    每个压缩包都附有数据表和数据来源 信心指数 1.投资者信心指数表 数据区间:20 08.04-2022.09,月度数据(数据库中该项数据的全部内容) 字段设置:全 选 全部字段: DeclareDate [发布日期] - YYYY-MM-DD SgnMonth [统计月度] - YYYY-MM IndexCode [指数编 码] - Q4001信心指数;Q4002国内经济基本面;Q4003国内经济政策; Q4004国际经济金融环境;Q4005股票估值;Q4006大盘乐观;Q4007大 盘反弹;Q4008大盘抗跌;Q4009买入; Name [指数名称] - 信心指 数;国内经济基本面;国内经济政策;国际经济金融环境;股票估值;大盘乐观;大盘反弹 ;大盘抗跌;买入; Value [当月值] - LastValue [上月值] - Mom [环比增减] - 压缩包所含文件: 数据样例: 2.消费者信心指数表 数据区间:1999.01-2022.09,月度数据(数据库中该项数据的全部内容 ) 字段设置:全选 全部字段: SgnMonth [统计月度] - YYYY-M M Expect

    使用Keras+TensorFlow进行目标检测-python源码.zip

    使用Keras+TensorFlow进行目标检测-python源码.zip

    node-v10.24.0-linux-x64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    深圳曙光医院触屏自适应html5手机医院网站模板下载 .zip

    触屏版自适应手机wap软件网站模板 触屏版自适应手机wap软件网站模板

    手机wap网站 仿腾讯新闻.zip

    触屏版自适应手机wap软件网站模板 触屏版自适应手机wap软件网站模板

    仿想去网触屏版html5手机wap网站模板购物网站模板.zip

    触屏版自适应手机wap软件网站模板 触屏版自适应手机wap软件网站模板

    lda代码-checkpoint-checkpoint.ipynb

    lda代码-checkpoint-checkpoint.ipynb

Global site tag (gtag.js) - Google Analytics