我的Panel上有一个JComboBox。其中一个弹出菜单项是“更多”,当我点击它时,我会获取更多菜单项并将它们添加到现有列表中。在此之后,我希望保持弹出菜单打开,以便用户意识到已经获取了更多项目,但弹出窗口关闭。我正在使用的事件处理程序代码如下
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == myCombo) {
JComboBox selectedBox = (JComboBox) e.getSource();
String item = (String) selectedBox.getSelectedItem();
if (item.toLowerCase().equals("more")) {
fetchItems(selectedBox);
}
selectedBox.showPopup();
selectedBox.setPopupVisible(true);
}
}
private void fetchItems(JComboBox box)
{
box.removeAllItems();
/* code to fetch items and store them in the Set<String> items */
for (String s : items) {
box.addItem(s);
}
}
我不明白为什么showPopup()和setPopupVisible()方法没有按预期运行。
答案 0 :(得分:4)
在fetchItems方法中添加以下行
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
box.showPopup();
}
}
如果你调用selectedBox.showPopup();在invokelater内部它也可以工作。
答案 1 :(得分:1)
覆盖JCombobox setPopupVisible metod
public void setPopupVisible(boolean v) {
if(v)
super.setPopupVisible(v);
}
答案 2 :(得分:0)
jComboBox1 = new javax.swing.JComboBox(){
@Override
public void setPopupVisible(boolean v) {
super.setPopupVisible(true); //To change body of generated methods, choose Tools | Templates.
}
};
答案 3 :(得分:0)
我找到了一些简单的解决方案,始终保持弹出窗口打开它可能对一些自定义的JComboBox有用,就像我在我的项目中那样,但是有点hacky。
public class MyComboBox extends JComboBox
{
boolean keep_open_flag = false; //when that flag ==true, popup will stay open
public MyComboBox(){
keep_open_flag = true; //set that flag where you need
setRenderer(new MyComboBoxRenderer()); //our spesial render
}
class MyComboBoxRenderer extends BasicComboBoxRenderer {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (index == -1){ //if popup hidden
if (keep_open_flag) showPopup(); //show it again
}
}
}
}