有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);
}

通过这两种方法,我获得了以下结果:

Picking a book

Borrowed book


共 (1) 个答案

  1. # 1 楼答案

    and when i hit a button that "loan a book", that book no longer appear.

    您需要从组合框的模型中删除所选项目

    因此,组合框的ActionListener中的代码如下所示:

    JComboBox comboBox = (JComboBox)e.getSource();
    DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
    Object item = comboBox.getSelectedItem();
    model.removeElement( item );