Java 自定义JComboBox顶部标签
希望这是一个简单的问题 从“提供自定义渲染器”部分的示例中,我可以创建一个类似JComboBox的Java 自定义JComboBox顶部标签,java,user-interface,swing,jcombobox,Java,User Interface,Swing,Jcombobox,希望这是一个简单的问题 从“提供自定义渲染器”部分的示例中,我可以创建一个类似JComboBox的 Picture 3 - Text 3 ------------------- Picture 1 - Text 1 Picture 2 - Text 2 Picture 3 - Text 3 Picture 4 - Text 4 Picture 5 - Text 5 其中图片3-文本3是当前选定的项目 有可能有一个自定义标签吗?比如 Text 3 ------------------- Pict
Picture 3 - Text 3
-------------------
Picture 1 - Text 1
Picture 2 - Text 2
Picture 3 - Text 3
Picture 4 - Text 4
Picture 5 - Text 5
其中图片3-文本3
是当前选定的项目
有可能有一个自定义标签吗?比如
Text 3
-------------------
Picture 1 - Text 1
Picture 2 - Text 2
Picture 3 - Text 3
Picture 4 - Text 4
Picture 5 - Text 5
组合框处于最小化状态时不显示图像的位置
我以前使用过JButton/undecorated popup JFrame来模拟这一点,但我想知道是否可以使用纯JComboBox
谢谢在渲染中似乎有3个函数调用与显示图像和文本相关: 塞蒂肯 塞特克斯 setFont 我没有编译这个示例,但我会尝试注释掉setIcon(icon);从函数GetListCellRenderComponent,这似乎显示了所选项目的图像 如果注释它会破坏代码,那么我会尝试使用空白图像或其他替代方法 有可能有一个自定义标签吗? 比如 对。相同的渲染器用于渲染下拉列表和组合框中的选定项。当“渲染器索引”为-1时,选定的值为渲染器,因此可以根据需要自定义渲染。比如:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class ComboBoxItemIcon extends JFrame
{
public ComboBoxItemIcon()
{
Vector model = new Vector();
model.addElement( new Item(new ImageIcon("copy16.gif"), "copy" ) );
model.addElement( new Item(new ImageIcon("add16.gif"), "add" ) );
model.addElement( new Item(new ImageIcon("about16.gif"), "about" ) );
JComboBox comboBox;
comboBox = new JComboBox( model );
comboBox.setRenderer( new ItemRenderer() );
getContentPane().add(comboBox, BorderLayout.SOUTH );
}
class ItemRenderer extends BasicComboBoxRenderer
{
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
Item item = (Item)value;
if (index == -1)
{
setText( item.getText() );
setIcon( null );
}
else
{
setText( item.getText() );
setIcon( item.getIcon() );
}
return this;
}
}
class Item
{
private Icon icon;
private String text;
public Item(Icon icon, String text)
{
this.icon = icon;
this.text = text;
}
public Icon getIcon()
{
return icon;
}
public String getText()
{
return text;
}
}
public static void main(String[] args)
{
JFrame frame = new ComboBoxItemIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
}
当
isSelected
为真时,使用setIcon(null)
关闭。但是,当项目是活动选择时,下拉列表中没有图像会产生不希望出现的效果。我认为,如果不设置JComboBox.setEditable(true),最小化的选定组件就不能完全独立于列表。或者可能设置一个操作侦听器,首先更改所选组件的模型(以便只有标签是合法的),然后以编程方式更新所选内容。这似乎需要做很多工作。不管怎样,我会给你分数,谢谢你让我知道索引的-1值。很好用!