How to set the text/name of a JList element in Java Swing?

I have created a list with 5 list elements.

When I do:

int currentIndex = list.getSelectedIndex();

I take the index of the current element. I would like to edit/modify the Text of the current element index. Is there any method for that?

e.g.

list.setText(CurrentIndex,"new text")
有帮助吗?

解决方案

Use the DefaultListModel. It has the method setElementAt(E element, int index) and add(int index, E element)

  • setElementAt(E element, int index) - Sets the component at the specified index of this list to be the specified element. The previous component at that position is discarded.

  • add(int index, E element) - Inserts the specified element at the specified position in this list.


You can initialize your JList with a DefaultListModel and then use all of the DefaultListModels methods

DefaultListModel model = new DefaultListModel();
JList list = new JList(model);

Then just use its methods

model.setElementAt("new text", index);
model.add(index, "new text");

See: DefaultListModel javadoc for more methods | How to use Lists tutorial

其他提示

//mouse click event

private void jListClientFileHeaderMappedMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here:

    JList<String> theList = (JList) evt.getSource();
    if (evt.getClickCount() == 2) { //

        JFrame frame = new JFrame();

        int index = theList.locationToIndex(evt.getPoint());
        if (index >= 0) {

            final JList list = ((JList) (evt.getComponent()));
            if (list.getSelectedIndex() != -1) {
                int i = list.getSelectedIndex();
                System.out.println(list.getSelectedIndex());
                DefaultListModel<String> listModel = (DefaultListModel<String>) jListClientFileHeaderMapped.getModel();
                Object result = JOptionPane.showInputDialog(frame, "value:");
                System.out.println(result);
                listModel.remove(i); //remove jlist item value 
                listModel.add(i, result.toString()); //add dialog text value

            }
        }
    }

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top