我有以下情况:在JCombobox中,首选大小基于最大的项目大小.但是,此计算不考虑为null呈现的值.它只关心模型中的值.因此,当渲染空值的文本大于另一个元素时,标签会被截断,并且我在末尾有三个点(…).我想避免这种情况.
这是我正在谈论的一个小演示:
import java.awt.Component;
import java.awt.GridBagLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestComboBox {
protected void initUI() {
JFrame frame = new JFrame(TestComboBox.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
JComboBox comboBox = new JComboBox(new Object[] { "Something", "Stuff", "Beep" });
comboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value == null) {
setText("No selection");
}
return comp;
}
});
comboBox.setSelectedItem(null);
panel.add(comboBox);
frame.add(panel);
frame.setSize(200, 100);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestComboBox().initUI();
}
});
}
}
我想知道你是否有任何建议.到目前为止,我的想法是扩展JComboBox,覆盖首选大小,还执行null值的呈现,并将调用的最大维度带到super.preferredSize和空值呈现之一.但我发现这有点令人失望.
我真的不喜欢不使用prototypeDisplayValue绝对不是一个选项,因为我不知道该下拉列表中的值.