简体   繁体   English

Java-如何在其他两个之间将元素添加到DefaultListModel?

[英]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. 显然,当我单击此“ btnInsertL”时,它会根据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. 它总是将新元素添加到列表的END,而忽略选择。 How could I add a new element according to the element that is already selected? 如何根据已选择的元素添加新元素? I suppose this involves element-indexes of the DefaultListModel. 我想这涉及DefaultListModel的元素索引。

Element 1
Element 2
Element 3

Let us suppose that the "Element 2" is selected. 让我们假设选择了“元素2”。 When I click in the "btnInsertL", I want that the FOURTH element goes between the element 2 and the element 3. 当我单击“ btnInsertL”时,我希望FOURTH元素位于元素2和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? 您检查了JavaDocs,对吗?

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

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

Thanks to the MadProgrammer I found the answer: 感谢MadProgrammer,我找到了答案:

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! 问题大于解决! :). :)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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