Java Swing:鼠标悬停在 JComboBox 项目上的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/480261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:11:14  来源:igfitidea点击:

Java Swing: Mouseover text on JComboBox items?

javaswing

提问by David Koelle

In Swing, is there a way to define mouseover text (or tool tip text) for each item in a JComboBox?

在 Swing 中,有没有办法为 JComboBox 中的每个项目定义鼠标悬停文本(或工具提示文本)?

采纳答案by MountainX

There is a much better way to do this than the ToolTipComboBoxanswer already given.

有比ToolTipComboBox已经给出的答案更好的方法来做到这一点。

First, make a custom ListCellRenderer:

首先,进行自定义ListCellRenderer

package com.example;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class ComboboxToolTipRenderer extends DefaultListCellRenderer {
    List<String> tooltips;

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus) {

        JComponent comp = (JComponent) super.getListCellRendererComponent(list,
                value, index, isSelected, cellHasFocus);

        if (-1 < index && null != value && null != tooltips) {
            list.setToolTipText(tooltips.get(index));
        }
        return comp;
    }

    public void setTooltips(List<String> tooltips) {
        this.tooltips = tooltips;
    }
}

Then use it like this:

然后像这样使用它:

JComboBox comboBox = new JComboBox();
ComboboxToolTipRenderer renderer = new ComboboxToolTipRenderer();
comboBox.setRenderer(renderer);
...
//make a loop as needed
comboBox.addItem(itemString);
tooltips.add(tooltipString);
...
renderer.setTooltips(tooltips);

回答by Paul Tomblin

I've never tried it, but you should be able to define a ListCellRenderer, and have it return a JLabel or whatever with a tool tip.

我从未尝试过,但您应该能够定义一个 ListCellRenderer,并让它返回一个 JLabel 或带有工具提示的任何内容。

回答by Boris Pavlovi?

Here's little bit fixed code from an online example:

这是来自在线示例的一些固定代码:

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

/**
 * @version 1.0 06/05/99
 */
public class ToolTipComboBox extends JFrame {

  /**
     * 
     */
    private static final long serialVersionUID = 2939624252688908292L;

String[] items = { "jw", "ja", "la" };

  String[] tooltips = { "Javanese ", "Japanese ", "Latin " };

  public ToolTipComboBox() {
    super("ToolTip ComboBox Example");

    JComboBox combo = new JComboBox(items);
    combo.setRenderer(new MyComboBoxRenderer());

    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(combo);
  }

  class MyComboBoxRenderer extends BasicComboBoxRenderer {
    /**
     * 
     */
    private static final long serialVersionUID = 2746090194775905713L;

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {
      if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
        if (-1 < index) {
          list.setToolTipText(tooltips[index]);
        }
      } else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
      }
      setFont(list.getFont());
      setText((value == null) ? "" : value.toString());
      return this;
    }
  }

  public static void main(String args[]) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}

    ToolTipComboBox frame = new ToolTipComboBox();
    frame.addWindowListener(new WindowAdapter() {
      @Override
    public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize(200, 140);
    frame.setVisible(true);
  }
}

回答by Michael Myers

If your combo box is not editable, use setRenderer(ListCellRenderer). If it is editable, use setEditor(ComboBoxEditor), because:

如果您的组合框不可编辑,请使用setRenderer(ListCellRenderer). 如果它是可编辑的,请使用setEditor(ComboBoxEditor),因为:

The renderer is used if the JComboBox is not editable. If it is editable, the editor is used to render and edit the selected item.

如果 JComboBox 不可编辑,则使用渲染器。如果它是可编辑的,则编辑器用于渲染和编辑所选项目。

回答by gerardw

I like the simplicity of MountainX's solution but not the lack of encapsulation. An alternate solution which has more moving parts, but they are pretty simple and reusable.

我喜欢 MountainX 解决方案的简单性,但不喜欢缺乏封装。一种具有更多活动部件的替代解决方案,但它们非常简单且可重复使用。

An interface:

一个接口:

public interface ToolTipProvider {
    public String getToolTip();
}

A wrapper class:

一个包装类:

public class ToolTipWrapper implements ToolTipProvider {
    final Object value;
    final String toolTip;

    public ToolTipWrapper(Object value, String toolTip) {
        this.value = value;
        this.toolTip = toolTip;
    }

    @Override
    public String getToolTip() {
        return toolTip; 
    }

    @Override
    public String toString() {
        return value.toString();
    }

}

And a variant of MountainX's renderer:

以及 MountainX 渲染器的一个变体:

public class ToolTipRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
         JComponent component = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected,
                cellHasFocus);
         String tip = null;
         if (value instanceof ToolTipProvider) {
             ToolTipProvider ttp = (ToolTipProvider) value;
             tip = ttp.getToolTip();
         }
         list.setToolTipText(tip);
         return component;
    }
}

with the adding now:

现在添加:

combobox.addItem(new ToolTipWrapper(itemString,tooltipString) );