Add / Remove JList

Hi, I need to select an element from a JList to another, removing it from the first. The method I created inserts only one element, overwrites the last one and does not delete the selected element from the first JList. Here is the code:

First list

private javax.swing.JList listaRosa; 

Filled with this method:

 private void visualizzaRosaButtonvisualizzaRosa(java.awt.event.ActionEvent evt) { // TODO add your handling code here: visualizzaSquadraSelezionata(); String fileSquadra; fileSquadra = squadraDaVisualizzare.getText(); DefaultListModel listModel = new DefaultListModel(); try { FileInputStream fstream = new FileInputStream("C:/Users/Franky/Documents/NetBeansProjects/JavaApplication5/src/javaapplication5/Rose/"+fileSquadra+""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { listModel.addElement(strLine); System.out.println(strLine); } listaRosa.setModel(listModel); //Close the input stream in.close(); } catch (Exception e) { } 

The second list, where I want to insert elements that remove from the first:

 private javax.swing.JList listaTitolari 

The working code does NOT work here:

 private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: DefaultListModel listModel = new DefaultListModel(); String daInserire; listModel.addElement(listaRosa.getSelectedValue()); listModel.removeElement(listaRosa.getSelectedValue()); listaTitolari.setModel(listModel); } 

thanks

+8
java swing add jlist
source share
2 answers

Problem

 listModel.addElement(listaRosa.getSelectedValue()); listModel.removeElement(listaRosa.getSelectedValue()); 

You can add an item and immediately delete it, since the operations of adding and deleting are in the same list structure.

Try

 private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) { DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel(); DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel(); if(lm2 == null) { lm2 = new DefaultListModel(); listaTitolari.setModel(lm2); } lm2.addElement(listaTitolari.getSelectedValue()); lm1.removeElement(listaTitolari.getSelectedValue()); } 
+16
source share

The best and easiest way to clean JLIST:

 myJlist.setListData(new String[0]); 
+10
source share

All Articles