How to add an array in JList ? So you can line by line or through a cycle
DefaultListModel dlm = new DefaultListModel(); jList1.setModel(dlm); dlm.addElement("1234"); Can I immediately array?
Lines are added and the second question appears, how to remove them from the list? I try this:
DefaultListModel dlm = new DefaultListModel(); jList1.setModel(dlm); int del = jList1.getSelectedIndex(); if(del == -1)System.out.println("-1"); else System.out.println(del); It always returns -1, respectively, use dlm.remove(); will not work.
But even if you specifically specify dlm.remove(4) , it crashes with an error dlm.remove(4) array boundary, although the Sheet is full. I tried the following:
private void jList1ValueChanged(ListSelectionEvent evt) { int idx = jList1.getSelectedIndex(); if(idx != -1) { System.out.println("Selected:" + Arr[idx]); } else System.out.println("Selected list"); } The result is even more interesting. He backed out. Because you click on this list box, and displays the selected line twice. Why, it is not clear.
In general, I ask for an example of deleting rows.
UPDATE
Regarding the addition. Made your class:
class AddStringToList { JList obj; AddStringToList(JList obj,String Array[]) { this.obj = obj; obj.setModel(new AbstractListModel() { String strings[] = Array; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(int i) { return strings[i]; } }); } } In principle, so satisfied. Regarding the removal. I can not declare JList, because it has already been announced and I cannot change it either NetBins does not allow to change. If I declare directly, then I will redraw the already created one. This is exactly the problem.
private void RemoveStringBtn_ActionPerformed(ActionEvent evt) { try { DefaultListModel dlm = new DefaultListModel(); jList1.setModel(dlm); int selected = jList1.getSelectedIndex(); if ( selected != -1 ) { dlm.remove( selected ); } } catch(Exception e) { System.out.println("Error:" + e); } } And I get Error null. And cleared the entire list.
I try this:
private void jList1ValueChanged(ListSelectionEvent evt) { if(!evt.getValueIsAdjusting()) { if(jList1.getSelectedIndex() != -1) { DefaultListModel dlm = new DefaultListModel(); jList1.setModel(dlm); dlm.remove(jList1.getSelectedIndex()); } else System.out.println("-1"); } } I get -1 and accordingly go beyond the bounds of the array. But the lines are in the Sheet, that is. Why exit?
Start by declaring the list model to be a field of the form class, or where you have the list:
private javax.swing.DefaultListModel<String> model = new DefaultListModel<>(); That's the point. Do not edit the fields where the environment inserts the code. Everywhere indicated // Variables declaration - do not modify. And does not change anything
dlm.remove(0)also gives an error? - Suvitruf ♦