Erroneous addition and removal of lines in JList
-
How do you add mass
JList
? It can be fast or over the cycle.DefaultListModel dlm = new DefaultListModel(); jList1.setModel(dlm); dlm.addElement("1234");
Can I have a mass?
The lines add and the second question arises, how do we remove them from the list? I'll say,
DefaultListModel dlm = new DefaultListModel(); jList1.setModel(dlm); int del = jList1.getSelectedIndex(); if(del == -1)System.out.println("-1"); else System.out.println(del);
Always returning -1 to use
dlm.remove();
It won't work.
But even if you specifydlm.remove(4)
, it's flying off with a mistake to cross the border, even though List is filled. Trying: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 results are even more interesting. He's back. That's what you put on a leafbox and turns out twice the line chosen. Why, I don't understand.
Anyway, I'm asking for an example of removing the lines.
UPDATE
About the addition. I did my 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, that's how it works. About the removal. I can't declare JList because he's already announced and I can't change either. If I make a direct announcement, I'll close the already created. That's 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 get Error null. And clear the list.
I'll say,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, outwards of the mass. But the lines are in Liste. Why the exit?
Start by declaring a model of a list to the field of shape or where you have a list:
private javax.swing.DefaultListModel<String> model = new DefaultListModel<>();
That's the sunset. It's not editing the fields where the environment sets the code.
Specified // Variables declaration - do not modify . And it doesn't change anything.
-
How do you add a mass to JList? It can be fast or over the cycle.
DefaultListModel
Only one element can be added. You can do your class with data storage.ArrayList
For example, inherited fromAbstractListModel
and add methods of work of taste (with challenges)fireXXXX
to reportJList
changes).The lines add and the second question arises, how do we remove them from the list? I'll be like,
If you're doing this right, first of all,
new DefaultListModel()
creates an empty model, secondly, the model removes 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() );
There's gonna be a third line on top of the line, and the console's gonna be out.
2
(line numbering 0)The results are even more interesting. He's back. That's what you say.
The leafbox is that, and it's two times the line chosen. Why,
I don't understand.It works. https://docs.oracle.com/javase/7/docs/api/javax/swing/ListSelectionModel.html#setValueIsAdjusting%28boolean%29 ♪ There's a characteristic in the event.
ValueIsAdjusting
which indicates that there are still changes in the choice, or no. You can squeeze a mouse and see the conclusion:jList1.addListSelectionListener( new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
System.out.println( "is adjusting? " + e.getValueIsAdjusting() );
}
});
Until you let go, every shift in the allocations will come in one communication with
true
And at the end, one withfalse
♪Example with disposal:
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:
Okay, you've got a NetBeans-- that sounds like a verdict.
Start by declaring a model of a list to the field of shape or where you have a list:
private javax.swing.DefaultListModel<String> model = new DefaultListModel<>();
Now put this model on your list, or through your realty editor.
model
(Type "Replaceable code, "model" meaning) or peeing in the design afterinitComponents
Like:public NewJFrame() {
initComponents();
jList1.setModel(model);
}
That's it. Next, when you need something from the model, use it.
model
♪What you're doing is crazy:
// данные, отображаемые 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 default sets anonymous class in the model.
AbstractListModel
And you will.ClassCastException
♪