简体   繁体   中英

How to clean whitespaces in jComboBox

I´m trying to make a jComboBox that contains books titles and when i hit a button that "loan a book", that book no longer appear. I was able to make all that work, but when I "lend a book", there is a blank space where it was located. This is the code that i tryied:

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

And also tryied this:

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

With both of them i obtain this results:

Picking a book

Borrowed book

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

You need to remove the selected item from the model of the combo box.

So the code in your ActionListener of the combo box would be something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM