java如何清理jComboBox中的空白
我试图制作一个包含书籍标题的jComboBox,当我点击“借书”按钮时,那本书就不再出现了。 我能够完成所有这些工作,但当我“借出一本书”时,它所在的地方有一片空白。 这是我尝试的代码:
private void cargarLibros()
{
String[] libros = new String[this.librosDisponibles()]; //librosDisponibles() returns the amount of books available
for(int i=0; i<this.librosDisponibles(); i++)
{
if(!(this.getBiblioteca().getLibros().get(i).prestado()))
{
libros[i] = this.getBiblioteca().getLibros().get(i).getTitulo(); //get the titles
}
}
jComboBox3.removeAll();
DefaultComboBoxModel modelo = new DefaultComboBoxModel(libros);
this.jComboBox3.setModel(modelo);
}
并尝试着这样做:
private void cargarLibros()
{
String[] libros = new String[this.librosDisponibles()];
for(int i=0; i<this.librosDisponibles(); i++)
{
if(!(this.getBiblioteca().getLibros().get(i).prestado()))
{
libros[i] = this.getBiblioteca().getLibros().get(i).getTitulo();
}
}
DefaultComboBoxModel modelo = (DefaultComboBoxModel)jComboBox3.getModel();
modelo.removeAllElements();
for(String libro : libros)
{
modelo.addElement(libro);
}
jComboBox3.setModel(modelo);
}
通过这两种方法,我获得了以下结果:
# 1 楼答案
您需要从组合框的模型中删除所选项目
因此,组合框的ActionListener中的代码如下所示: