java - 将项目添加到 java 中的 jlist 后,从自动完成组合框中删除该项目

标签 java swing combobox jlist glazedlists

将项目添加到 jlist 后,从自动完成组合框中删除该项目

这里我添加一个名为glazedlists_java15-1.9.0.jar

的jar文件

这是向 jpanel 添加字段的代码

            DefaultComboBoxModel dt=new DefaultComboBoxModel();
       comboBook = new JComboBox(dt);         
       comboBook.addItemListener(this);
       List<Book>books=ServiceFactory.getBookServiceImpl().findAllBook();
       Object[] elementBook = new Object[books.size()];         
        int i=0;
        for(Book b:books){
            elementBook[i]=b.getCallNo();
        //   dt.addElement(elementBook[i]);
            i++;
        }

        AutoCompleteSupport.install(comboBook, GlazedLists.eventListOf(elementBook));
        comboBook.setBounds(232, 151, 184, 22);
        issuePanel.add(comboBook);

        btnAdd = new JButton("+");
        btnAdd.addActionListener(this);
        btnAdd.setBounds(427, 151, 56, 23);
        issuePanel.add(btnAdd);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(232, 184, 184, 107);
        issuePanel.add(scrollPane);


        v=new Vector<String>();
        listBooks = new JList(v);
        scrollPane.setViewportView(listBooks);

         btnRemove = new JButton("-");
         btnRemove.addActionListener(this);
        btnRemove.setBounds(427, 185, 56, 23);
        issuePanel.add(btnRemove);

此处执行操作的代码..

 public void actionPerformed(ActionEvent e) {

    if(e.getSource()==btnAdd){

        DefaultComboBoxModel dcm = (DefaultComboBoxModel) comboBook.getModel();
        dcm.removeElementAt(index);
        // Add what the user types in JTextField jf, to the vector
          v.add(selectedBook);

          // Now set the updated vector to JList jl
          listBooks.setListData(v);

          // Make the button disabled
          jb.setEnabled(false);

    }
    else if(e.getSource()==btnRemove){
         // Remove the selected item
           v.remove(listBooks.getSelectedValue());

           // Now set the updated vector (updated items)
           listBooks.setListData(v);

    }

enter image description here

此处图像显示从组合框中添加一个项目到 jlist,然后该项目从组合框中隐藏或删除。

如果你们知道这一点,请在这里分享答案..谢谢!!!

最佳答案

从您的描述和代码中可以看出,您只是使用 GlazedLists 便捷方法来设置初始自动完成组件,但您没有使用 GlazedLists 的基本部分将各种元素拼接在一起:事件列表。

当然 - 您已经派生了一个一次性事件列表来填充自动完成安装,但 GlazedLists 确实希望您利用事件列表来保存您的对象,而不是在快速交换期间。像 JComboBox 和 JList 这样的纯 Java Swing 组件会迫使您采用数组和 vector 的方式,但是如果您坚持使用各种 EventList 实现作为基本集合类,GlazedLists 会提供许多帮助器类。它具有用于组合框和 jlist 模型的类以及选择模型类,这些类可以方便地链接 EventLists 和 Swing 组件,一旦您沿着这条路线走下去,您就可以真正简化您的代码。

这是我认为您想要实现的目标的一个非常粗略的示例。我认为代码本身就说明了一切,而不是我再胡言乱语。 注意:我使用的是 GlazedLists 1.8。

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.swing.AutoCompleteSupport;
import ca.odell.glazedlists.swing.EventComboBoxModel;
import ca.odell.glazedlists.swing.EventListModel;
import ca.odell.glazedlists.swing.EventSelectionModel;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Comparator;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;

/**
 *
 * @author Andrew Roberts
 */
public class GlazedListsAutocompleteTest {

    private JFrame mainFrame;
    private JComboBox availableItems;
    private EventList<Book> books = new BasicEventList<Book>();
    private EventList<Book> selectedBooks;

    public GlazedListsAutocompleteTest() {
        populateAvailableBooks();
        createGui();
        mainFrame.setVisible(true);
    }

    private void populateAvailableBooks() {
        books.add(new Book("A Tale of Two Cities"));
        books.add(new Book("The Lord of the Rings"));
        books.add(new Book("The Hobbit"));
        books.add(new Book("And Then There Were None"));
    }

    private void createGui() {

        mainFrame = new JFrame("GlazedLists Autocomplete Example");
        mainFrame.setSize(600, 400);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //EventComboBoxModel<Book> comboModel = new EventComboBoxModel<Book>(books);
        availableItems = new JComboBox();
        final SortedList<Book> availableBooks = new SortedList<Book>((BasicEventList<Book>) GlazedLists.eventList(books), new BookComparitor());

        selectedBooks = new SortedList<Book>(new BasicEventList<Book>(), new BookComparitor());

        AutoCompleteSupport autocomplete = AutoCompleteSupport.install(availableItems, availableBooks);

        JButton addButton = new JButton("+");
        addButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventComboBoxModel<Book> comboModel = (EventComboBoxModel<Book>) availableItems.getModel();
                try {
                    Book book = (Book) comboModel.getSelectedItem();
                    selectedBooks.add(book);
                    availableBooks.remove(book);
                } catch (ClassCastException ex) {
                    System.err.println("Invalid item: cannot be added.");
                }

            }
        });

        final EventListModel listModel = new EventListModel(selectedBooks);
        final EventSelectionModel selectionModel = new EventSelectionModel(selectedBooks);

        JButton removeButton = new JButton("Remove");
        removeButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventList<Book> selectedListItems = selectionModel.getSelected();
                for (Book book : selectedListItems) {
                    selectedBooks.remove(book);
                    availableBooks.add(book);
                }
            }
        });

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(availableItems, BorderLayout.CENTER);
        panel.add(addButton, BorderLayout.EAST);


        JList selectedItemsList = new JList(listModel);
        selectedItemsList.setSelectionModel(selectionModel);
        mainFrame.setLayout(new BorderLayout());
        mainFrame.getContentPane().add(panel, BorderLayout.NORTH);
        mainFrame.getContentPane().add(selectedItemsList, BorderLayout.CENTER);
        mainFrame.getContentPane().add(removeButton, BorderLayout.SOUTH);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
          new GlazedListsAutocompleteTest();
        }
    });
    }

    class Book {
        private String title;

        public Book() {
        }

        public Book(String title) {
            this.title = title;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        @Override
        public String toString() {
            return getTitle();
        }   
    }

    class BookComparitor implements Comparator<Book> {

        @Override
        public int compare(Book b1, Book b2) {
            return b1.getTitle().compareToIgnoreCase(b2.getTitle());
        }
    }
}

关于java - 将项目添加到 java 中的 jlist 后,从自动完成组合框中删除该项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21881037/

相关文章:

java - 如何让 dbunit 与 MySQL 枚举数据类型配合使用?

java - 如何从 JFrame 中删除 JscrollPane?

java - Java Preference API 可以作为避免读取文件的替代方案吗?

wpf - 组合框丢失 SelectedIndex

javascript - 获取有关组合框更改的用户详细信息

Java Swing : How to handle events that occur in subclass

java - 如何从 Google Custom Search API 获取超过 100 个结果

java - 如何在java中更新txt文件

java - 第一次设置日期时的 JDatePicker 错误

wpf - 使用 mvvm 的可编辑 ComboBox 设置插入符位置