我对JComboBoxes和长字符串有问题。结果是JComboBox对于JFrame来说太长了,因此它无法显示整个框。
在这里,我有一些代码来显示我的问题:
JFrame frame = new JFrame();
frame.setSize(500, 500);
JPanel panel = new JPanel();
DesignGridLayout layout = new DesignGridLayout(panel);
Vector<ArrayList<String>> content = new Vector<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
list.add("12345");
list.add("abcde");
list.add("12345");
list.add("abcde");
list.add("12345");
list.add("abcde");
list.add("12345");
list.add("abcde");
list.add("12345");
list.add("abcde");
list.add("12345");
list.add("abcde");
content.add(list);
ComboBoxFullMenu<ArrayList<String>> combobox = new ComboBoxFullMenu<ArrayList<String>>(content);
combobox.setRenderer(new 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);
ArrayList<String> array = (ArrayList<String>) value;
if (!array.isEmpty())
{
String text = "";
for (String info : array)
{
text += info + "; ";
}
setText(text);
}
return this;
}
});
AutoCompleteDecorator.decorate(combobox, new ObjectToStringConverter()
{
@Override
public String getPreferredStringForItem(Object object)
{
if (object != null)
{
if (object instanceof ArrayList)
{
ArrayList<String> list = (ArrayList<String>) object;
String text = "";
for (String info : list)
{
text += info + "; ";
}
return text;
}
else
{
return object.toString();
}
}
return null;
}
});
layout.row().grid().add(combobox);
frame.add(panel);
frame.setVisible(true);
这是ComboBoxFullMenu类:
public class ComboBoxFullMenu<E> extends JComboBox<E>
{
/**
*
*/
private static final long serialVersionUID = 1L;
public ComboBoxFullMenu(Vector<E> items)
{
super(items);
addActionListener(this);
}
public ComboBoxFullMenu()
{
super();
addActionListener(this);
}
public ComboBoxFullMenu (DefaultComboBoxModel<E> defaultComboBoxModel)
{
super(defaultComboBoxModel);
addActionListener(this);
}
/**
* Small hack to get pop up menu size bigger enough to show items even though
* the combo box size could be smaller
* */
private boolean layingOut = false;
@Override
public void doLayout()
{
try
{
layingOut = true;
super.doLayout();
}
finally
{
layingOut = false;
}
}
@Override
public Dimension getSize()
{
Dimension dim = super.getSize();
if ( !layingOut )
{
dim.width = Math.max(dim.width, getPreferredSize().width);
}
return dim;
}
}
我还尝试使用DefaultListCellRenderer和ObjectTroStringConverter以较短的方式显示所选项目,但是我需要在dropdownmenu中查看所有信息,并且我认为JComboBox会计算最长项目的宽度?
希望您能理解我的问题,否则请告诉我。
最佳答案
签出Combo Box Popup是允许您控制弹出窗口的宽度。您可以设置宽度
到最大字符串的大小,或者
指定最大宽度。
然后,如果字符串大于指定的宽度,则可以在弹出窗口中打开滚动。