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

  • Please show the minimum compile code. This means that the code should be compiled and there should not be extra elements in it. - LEQADA
  • And how many items in the list? dlm.remove(0) also gives an error? - Suvitruf
  • @Suvitruf, but gives an error output for the array. - Kamenev_D
  • Already hands fall. Can someone thread an example in NetBins with a single listbox and a button with a delete code? Or send by mail. - Kamenev_D

1 answer 1

How to add an array in JList? So you can line by line or through a cycle

DefaultListModel allows you to add only one element. You can make your own class, with data storage in ArrayList for example, inheriting from AbstractListModel and adding work methods to taste (with calls to fireXXXX to report changes to the JList ).

Lines are added and the second question appears, how to remove them from the list? I try this:

If you try this directly, then, first of all, new DefaultListModel() creates an empty model, and secondly, setting the model resets the selection of elements. You can write:

 JList<String> jList1 = new JList<String>(); DefaultListModel<String> dlm = new DefaultListModel<>(); jList1.setModel( dlm ); dlm.addElement("1234"); dlm.addElement("1235"); dlm.addElement("1236"); dlm.addElement("1237"); jList1.setSelectedIndex( 2 ); System.out.println( jList1.getSelectedIndex() ); 

The third line from the top will be selected, the console will display 2 (numbering lines with 0)

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.

This is ListSelectionModel works. In the event there is the ValueIsAdjusting property, which indicates ValueIsAdjusting is continuing or not. You can hold the mouse and see the output:

 jList1.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { System.out.println( "is adjusting? " + e.getValueIsAdjusting() ); } }); 

Until you release, each change of selection will receive one message with true , and at the end one with false .

Example with deletion:

 public class JListExample { public static void createUi() { JFrame frame = new JFrame("JList example"); frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE ); JPanel content = new JPanel( new BorderLayout() ); JList<String> jList1 = new JList<String>(); DefaultListModel<String> dlm = new DefaultListModel<>(); jList1.setModel( dlm ); dlm.addElement("1234"); dlm.addElement("1235"); dlm.addElement("1236"); dlm.addElement("1237"); content.add( jList1, BorderLayout.CENTER ); JButton button = new JButton( "delete!" ); button.setEnabled( false ); jList1.addListSelectionListener( event -> { if ( !event.getValueIsAdjusting() ) { // getSelectedIndex возвращает индекс самой верхней выбранной строки button.setEnabled( jList1.getSelectedIndex() != -1 ); } }); button.addActionListener( event -> { int selected = jList1.getSelectedIndex(); if ( selected != -1 ) { dlm.remove( selected ); } }); content.add( button, BorderLayout.SOUTH ); frame.setContentPane( content ); frame.setSize( 640, 480 ); frame.setVisible( true ); } public static void main(String[] args) { SwingUtilities.invokeLater( JListExample::createUi ); } } 

Update:

Ok, you have a NetBeans form editor - it sounds like a sentence.

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<>(); 

Now set this model to your list either through the model property editor (type "code to be changed", the value "model"), or by typing in the constructor after initComponents directly like this:

 public NewJFrame() { initComponents(); jList1.setModel(model); } 

Everything. Next, when you need something from the model - use model .

What you are doing is simply insane:

 // данные, отображаемые JList хранятся в модели if(jList1.getSelectedIndex() != -1) { // вы создали новую ПУСТУЮ модель DefaultListModel dlm = new DefaultListModel(); // вы назначили новую пустую модель JList-у jList1.setModel(dlm); // пуф, все содержимое пропадает // вы удаляете из новой ПУСТОЙ модели элемент, которого там нет dlm.remove(jList1.getSelectedIndex()); // бабах, вылетает ArrayIndexOutOfBounds } 

You could do:

 // взять у JList текущую модель, привести ее к типу DefaultListModel DefaultListModel dlm = (DefaultListModel)jList1.getModel() 

but NetBeans defaults to the model anonymous class from AbstractListModel , and you get a ClassCastException .