SortedListModel只添加一个项目

时间:2018-01-22 16:16:53

标签: java swing

我有一个名为comandaDescriptionListModel的SortedListModel:

private SortedListModel comandaDescriptionListModel;

我的应用程序中有其他SortedListModels,但是这个在1个元素后面无法添加项目。只添加1个元素,没有任何意义。

        btnAddComanda.addActionListener(new ActionListener() {
            @SuppressWarnings("unchecked")
            @Override
            public void actionPerformed(ActionEvent arg0) {
                JPanel addPanel = new JPanel();
                addPanel.add(new JLabel("Descrição:"));
                JTextField comandaDescriptionField = new JTextField();
                comandaDescriptionField.setPreferredSize(new Dimension(200, 24));
                addPanel.add(comandaDescriptionField);
                comandaDescriptionField.requestFocusInWindow();
                String comandaName = "C" + Integer.toString(comandaListModel.getSize()+1); 
                int result = JOptionPane.showConfirmDialog(null, addPanel, "Adicionar comanda",
                        JOptionPane.OK_CANCEL_OPTION);
                if (result == JOptionPane.OK_OPTION) {
                    if (comandaListModel.getSize() == 0) {
                        productComboBox.setEnabled(true);
                        btnAddProduct.setEnabled(true);
                    }
                    String comandaDescription = comandaDescriptionField.getText();
                    getCurrentCashRegister().addComanda(comandaName, comandaDescription);
                    // Comanda description model not adding items,
                    // Need to fix it
                    comandaListModel.addElement(comandaName);
                    comandaDescriptionListModel.addElement(comandaDescription); // HERE <<<
                    comandaList.setSelectedIndex(comandaList.getLastVisibleIndex());
                    clearProductComboBox();
                    updateProductComboBox();
                }
            }
        });

以下是截图:

enter image description here

在“descrição”下,它应该继续“b”和“c”。我只能认为这是一个错误。是否有一些摆动错误在同时附加到多个列表时会导致问题?

1 个答案:

答案 0 :(得分:0)

当我处理多个JList组件时,我会以自己的方式执行它,并且还可以使用所有给定的工具。

Multi JList Example

为什么不,我使用下面的源代码?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MultiListExample extends JFrame {
    private static final long serialVersionUID = 1L;

    private JTextField textField;
    private JButton addBtn, removeBtn;
    private JList<String> list1, list2, list3;
    private DefaultListModel<String> dlm1, dlm2, dlm3;

    public MultiListExample() {
        init();
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | UnsupportedLookAndFeelException ex) {
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MultiListExample();
            }
        });
    }

    private void init() {
        setTitle("Multi List Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(450, 100, 300, 300);

        textField = new JTextField();
        textField.setFont(new Font("Dialog", Font.PLAIN, 15));
        add(textField, BorderLayout.PAGE_START);

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

        addBtn = new JButton("Add Element");
        addBtn.setFocusPainted(false);
        addBtn.setFont(textField.getFont());
        panel.add(addBtn, BorderLayout.PAGE_START);

        JPanel innerPanel = new JPanel(new GridLayout(1, 3));
        panel.add(innerPanel, BorderLayout.CENTER);

        dlm1 = new DefaultListModel<String>();
        dlm1.addElement("Apple");
        dlm1.addElement("Avocado");
        dlm1.addElement("Banana");
        dlm1.addElement("Jambul");
        list1 = new JList<String>(dlm1);
        list1.setFont(textField.getFont());
        innerPanel.add(list1);

        dlm2 = new DefaultListModel<String>();
        dlm2.addElement("Currant");
        dlm2.addElement("Cherry");
        dlm2.addElement("Cloudberry");
        dlm2.addElement("Raisin");
        list2 = new JList<String>(dlm2);
        list2.setFont(textField.getFont());
        list2.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 1, Color.BLACK));
        innerPanel.add(list2);

        dlm3 = new DefaultListModel<String>();
        dlm3.addElement("Dragonfruit");
        dlm3.addElement("Durian");
        dlm3.addElement("Feijoa");
        dlm3.addElement("Fig");
        dlm3.addElement("Grape");
        list3 = new JList<String>(dlm3);
        list3.setFont(textField.getFont());
        innerPanel.add(list3);

        removeBtn = new JButton("Remove Element");
        removeBtn.setFocusPainted(false);
        removeBtn.setFont(textField.getFont());
        add(removeBtn, BorderLayout.PAGE_END);

        list1.setSelectedIndex(dlm1.getSize() - 1);
        list2.setSelectedIndex(dlm2.getSize() - 1);
        list3.setSelectedIndex(dlm3.getSize() - 1);

        textField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                addElementListener();
            }
        });

        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                addElementListener();
            }
        });

        removeBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                if (dlm1.getSize() > 0)
                    dlm1.remove(list1.getSelectedIndex());

                if (dlm2.getSize() > 0)
                    dlm2.remove(list2.getSelectedIndex());

                if (dlm3.getSize() > 0)
                    dlm3.remove(list3.getSelectedIndex());

                if (dlm1.getSize() > 0)
                    list1.setSelectedIndex(0);

                if (dlm2.getSize() > 0)
                    list2.setSelectedIndex(0);

                if (dlm3.getSize() > 0)
                    list3.setSelectedIndex(0);
            }
        });

        setVisible(true);
    }

    private void addElementListener() {
        if (textField.getText().length() > 2) {
            addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list1, dlm1);
            addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list2, dlm2);
            addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list3, dlm3);
        }
    }

    private void addSortAndRemoveDuplicates(String element, JList<String> list, DefaultListModel<String> model) {
        // Here doing all DefaultListModel operations explicitly.
        if (!model.contains(element)) {
            model.addElement(element);

            int size = model.getSize();
            String[] elements = new String[size];

            for (int i = 0; i < size; i++)
                elements[i] = (String) model.getElementAt(i);

            Arrays.sort(elements);
            model.removeAllElements();

            for (int i = 0; i < size; i++)
                model.addElement(elements[i]);

            list.setSelectedIndex(model.getSize() - 1);
        }
    }

    private String firstLetterCapWord(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
    }

}