简体   繁体   中英

Java - How to add an element to a DefaultListModel between other two?

Here is it:

btnInsertL.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            String textField1Content = textField1.getText();
            if (textField1.getText().contains("Nova Categoria")) {
            } else {
                modelL.addElement(textField1Content);
            }
        }
    });

Obviously, when I click in this "btnInsertL", it adds to my list a new element according to the name of the textField1. But with this, we have a subtle problem if we want the process to be more "dynamic":

It always add the new element to the END of the list, ignoring the selection. How could I add a new element according to the element that is already selected? I suppose this involves element-indexes of the DefaultListModel.

Element 1
Element 2
Element 3

Let us suppose that the "Element 2" is selected. When I click in the "btnInsertL", I want that the FOURTH element goes between the element 2 and the element 3.

Well, I think that this question is not that useless, I hope it helps someone too. I thank you all very much for the attention.

You checked the JavaDocs right?

Take a look at DefaultListModel.add(int, E)

检查DefaultListModel.add(int, E)并使用ActionEvent的getSource()方法查看选择了哪个按钮。

Thanks to the MadProgrammer I found the answer:

btnInsertL.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            String textField1Content = textField1.getText();
            if (textField1.getText().contains("Nova Categoria")) {
            } else {
                modelL.add(listL.getSelectedIndex() + 1,textField1Content);
            }
        }
    });

Problem more than solved! :).

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