使用可编辑组合框时,DefaultListCellRenderer 无法正确呈现空字符串
Posted
技术标签:
【中文标题】使用可编辑组合框时,DefaultListCellRenderer 无法正确呈现空字符串【英文标题】:DefaultListCellRenderer does not render empty String correctly when using an editable combo box 【发布时间】:2015-08-25 15:06:44 【问题描述】:我已将自定义渲染器安装到可编辑的 JCombobox,但渲染空字符串时遇到问题。 您知道如何以正确/相似的高度显示空项目吗?或者这是一个 Java 错误?
请参阅以下示例和屏幕截图以了解区别:
package combo;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class MyComboBox
private final class CustomCellRenderer extends DefaultListCellRenderer
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
private Vector<String> listSomeString = new Vector<String>();
private JComboBox someComboBox = new JComboBox(listSomeString);
private JComboBox editableComboBox = new JComboBox(listSomeString);
private JComboBox non_EditableComboBox = new JComboBox(listSomeString);
private JFrame frame;
public MyComboBox()
listSomeString.add("");
listSomeString.add("-");
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
someComboBox.setPrototypeDisplayValue("Speed reading");
someComboBox.setEditable(true);
editableComboBox.setPrototypeDisplayValue("Speed reading");
editableComboBox.setEditable(true);
editableComboBox.setRenderer(new CustomCellRenderer());
frame = new JFrame();
frame.setLayout(new GridLayout(0, 1, 10, 10));
frame.add(someComboBox);
frame.add(editableComboBox);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
@Override
public void run()
MyComboBox aCTF = new MyComboBox();
);
【问题讨论】:
【参考方案1】:JComboBox
不使用DefaultListCellRenderer
。如果你打电话
System.out.println(editableComboBox.getRenderer());
您会注意到,JComboBox
使用了 BasicComboBoxRenderer
。
你只需要把它改成
private final class CustomCellRenderer extends BasicComboBoxRenderer
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
【讨论】:
以上是关于使用可编辑组合框时,DefaultListCellRenderer 无法正确呈现空字符串的主要内容,如果未能解决你的问题,请参考以下文章
具有来自 itemsource 或用户输入的选定值(路径)的可编辑组合框