【问题标题】:How to clean whitespaces in jComboBox如何清除 jComboBox 中的空格
【发布时间】:2018-11-12 19:35:41
【问题描述】:

我正在尝试制作一个包含书名的 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

【问题讨论】:

    标签: java swing jcombobox


    【解决方案1】:

    当我点击“借书”按钮时,该书不再出现。

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

    所以组合框的 ActionListener 中的代码类似于:

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

    【讨论】:

      猜你喜欢
      • 2011-08-02
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多