我有一个组合框,其中的项目是Objects,其字符串值可能很长。而不是让盒子更长,我希望鼠标浮动时出现全文。我怎么能这样做?
答案 0 :(得分:1)
以下是使用custom cell renderer。
的示例如上所述,您可以通过以下方式使用我的示例:
ToolTipRenderer.addRenderer(jComboBox, foo -> foo.getTheLongString());
(或者如果你不想要通用/ Java 8的东西,你可以复制和重构它。)
我基本上在这里使用装饰器模式,而不是像扩展DefaultListCellRenderer
那样。这样,如果JComboBox
已经使用了不同的行为,则保持行为。你真正关心设置工具提示的是组件是否是JComponent
的一些子类。
import java.util.Objects;
import java.util.function.Function;
import javax.swing.ListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JComponent;
import java.awt.Component;
public class ToolTipRenderer<E> implements ListCellRenderer<E> {
private final ListCellRenderer<? super E> delegate;
private final Function<E, String> toStringFn;
public ToolTipRenderer(ListCellRenderer delegate,
Function<E, String> toStringFn) {
this.delegate = Objects.requireNonNull(delegate);
this.toStringFn = Objects.requireNonNull(toStringFn);
}
@Override
public Component getListCellRendererComponent(JList<? extends E> list,
E value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component result =
delegate.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
if (result instanceof JComponent) {
// if you don't want to use generics,
// replace this with
// = value.getTheLongString();
String ttText = toStringFn.apply(value);
((JComponent) result).setToolTipText(ttText);
// I was not sure if you wanted
// something like this too.
// if (result instanceof JLabel) {
// ((JLabel) result).setText(value.getTheShortString());
// }
}
return result;
}
// This is an example of how it should be used.
// Pass the ToolTipRenderer the previous renderer
// from comboBox.getRenderer().
public static <E> void addRenderer(JComboBox<E> comboBox,
Function<E, String> toStringFn) {
ListCellRenderer<? super E> delegate = comboBox.getRenderer();
comboBox.setRenderer(new ToolTipRenderer<E>(delegate, toStringFn));
}
}
答案 1 :(得分:1)
基本解决方案是提供ListCellRenderer
,将返回的Component
toolTipText
属性设置为您需要的适当值
DefaultListCellRenderer
从JLabel
延伸,因此您可以简单地使用toolTipText
方法来提供永久性的&#34;扩展&#34;例如,你想要的文字。
public class ToolTipListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
// I'd extract the basic "text" representation of the value
// and pass that to the super call, which will apply it to the
// JLabel via the setText method, otherwise it will use the
// objects toString method to generate a representation
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setToolTipText("To what ever you need based on the value that has been passsed");
return this;
}
}