質問

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