How to move items from one JList to other

Can u pls help me out to implement this(I m using Netbeans 5.5):

I want to move items from one JList to other thru a ADD button placed between JLists, I am able to add element on Right side JList but as soon as compiler encounterremoveElementAt() it throws Array Index Out of Bound Exception

and if I use

removeElement() it removes all items from left side JList and returns value false.

Pls have a look at this code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

Object selItem = jList1.getSelectedValue();

int selIndex = jList1.getSelectedIndex();

DefaultListModel model = new DefaultListModel();

jList2.setModel(model);

model.addElement(selItem);

DefaultListModel modelr = new DefaultListModel();

jList1.setModel(modelr);

flag = modelr.removeElement(selItem);

//modelr.removeElementAt(selIndex);

System.out.println(flag);

}

[1028 byte] By [singhvisuna] at [2007-11-27 9:05:30]
# 1

I have some troubles wth JList too.

jListleft={leftFirst,leftSecond,leftThird};

jListRight{rightFirst,rightSecond,rightThird};

Also you have a JButton, that "moves" elements from left list to the right list

So if you want to move element "leftSecond" to right JList

you will get:

jListleft={leftSecond,leftThird};

jListRight{rightFirst,rightSecond,rightThird,leftFirst};

Did I understand your idea?

Holoda at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 2

Use code formatting when posting code:

http://forum.java.sun.com/help.jspa?sec=formatting

Why are you setting a new model for both lists?

Just add the new item to the second list and remove it from the first one:

Read in the tutorial Adding Items to and Removing Items from a List

http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#mutable

Set the model for both list to be DefaultListModel when you create the lists.

jList1 = new JList(new DefaultListModel());

jList2 = new JList(new DefaultListModel());

Then you can just do this:

Object selItem = jList1.getSelectedValue();

((DefaultListModel) jList1.getModel()).removeElement(selItem);

((DefaultListModel) jList2.getModel()).addElement(selItem);

Rodney_McKaya at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 3
Ya, u have understand the problem exactly, now do u have any clue to implement it in Netbeans 5.5Thanks for ur time.
singhvisuna at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 4
> Ya, u have understand the problem exactly, now do u> have any clue to implement it in Netbeans 5.5I don't use NetBeans, but I'll bet it allows you to edit source code. Do so, as Rodney_McKay outlines above.
mbmerrilla at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 5

hi Rodney_McKay,

Thanks for valuable time but my problem is as it is, pls have a look what I have done and what more can b done in this direction.

Here is the code:

import javax.swing.DefaultListModel;

import javax.swing.JList;

public class twoList extends javax.swing.JFrame {

/** Creates new form twoList */

public twoList() {

initComponents();

}

//The code shown below is automatically generated and we can抰 edit this code

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();

jList1 = new javax.swing.JList();

jButton1 = new javax.swing.JButton();

jScrollPane2 = new javax.swing.JScrollPane();

jList2 = new javax.swing.JList();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jList1.setModel(new javax.swing.AbstractListModel() {

String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };

public int getSize() { return strings.length; }

public Object getElementAt(int i) { return strings; }

});

jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {

public void valueChanged(javax.swing.event.ListSelectionEvent evt) {

jList1ValueChanged(evt);

}

});

jScrollPane1.setViewportView(jList1);

jButton1.setText("ADD>>");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

jScrollPane2.setViewportView(jList2);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(31, 31, 31)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jButton1)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(78, Short.MAX_VALUE))

);

layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(62, 62, 62)

.addComponent(jButton1))

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))

.addContainerGap(159, Short.MAX_VALUE))

);

layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});

pack();

}// </editor-fold>

//automatic code ends here

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

jList1 = new JList(new DefaultListModel());

jList2 = new JList(new DefaultListModel());

Object selItem = jList1.getSelectedValue();

System.out.println(selItem);

((DefaultListModel) jList1.getModel()).removeElement(selItem);

((DefaultListModel) jList2.getModel()).addElement(selItem);

}

//Now trying with this code it is neither adding or removing and the value 憂ull?is coming in 憇elItem?.It may be bcoz JList and Jlist are already instantiated in automatic code. So, I tried this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

Object selItem = jList1.getSelectedValue();

System.out.println(selItem);

((DefaultListModel) jList1.getModel()).removeElement(selItem);

((DefaultListModel) jList2.getModel()).addElement(selItem);

}

//Now with this as soon as I click on 慾Button1? it is throwing this error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: twoList$1 cannot be cast to javax.swing.DefaultListModel

at twoList.jButton1ActionPerformed(twoList.java:105)

at twoList.access$100(twoList.java:13)

at twoList$3.actionPerformed(twoList.java:50)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)

at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)

at java.awt.Component.processMouseEvent(Component.java:6038)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)

at java.awt.Component.processEvent(Component.java:5803)

at java.awt.Container.processEvent(Container.java:2058)

at java.awt.Component.dispatchEventImpl(Component.java:4410)

at java.awt.Container.dispatchEventImpl(Container.java:2116)

at java.awt.Component.dispatchEvent(Component.java:4240)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)

at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)

at java.awt.Container.dispatchEventImpl(Container.java:2102)

at java.awt.Window.dispatchEventImpl(Window.java:2429)

at java.awt.Component.dispatchEvent(Component.java:4240)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

singhvisuna at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 6

private void jButtonMoveItemsActionPerformed(java.awt.event.ActionEvent evt) {

//get access through interface ListModel to left and Right JLists's models

ListModel leftLM = jListLeft.getModel();

ListModel rightLM = jListRight.getModel();

int leftSelected = jListLeft.getSelectedIndex();//index of selected Left JList item

Object selectedItem = jListLeft.getSelectedValue(); //value of selected Left JList item

DefaultListModel leftDLM = new DefaultListModel(); //Create new instance of DefaultListModel for left JList

DefaultListModel rightDLM = new DefaultListModel(); //Create new instance of DefaultListModel for right JList

//copy existing items to DefaultListModel

for(int i=0;i<leftLM.getSize();i++){

if(i == leftSelected){ //but we have to skip selected item

continue;

}//if

else{

leftDLM.addElement(leftLM.getElementAt(i)); //element added

}//else

}//for

jListLeft.setModel(leftDLM);//set new model for left JList without "deleted" item

System.out.println(leftDLM);//let's print it and see the new model

//copy items from right ListModel to new DefaultListModel

for(int i=0;i<rightLM.getSize();i++){

rightDLM.addElement(rightLM.getElementAt(i));

}

rightDLM.addElement(selectedItem); //Item from left List added

jListRight.setModel(rightDLM); //set new model with added item

System.out.println(rightDLM);//let's print and see the new model

//accomplished!!!! Yah!!!

}

This Is my solution.

It works 100%

I've used NetBeans 5.5 + GUI Builder

I've made JFrame Form

I've put there 2JLists: jListLeft and jListRight

I've put there JButton: jButtonMoveItems

So You can see ActionPerformed event to this Button.

P.S

Do not forget to add something to JList models while you are designing (do it through "Properties")

P.P.S.

Code it pretty long, but you can easilly make it shorter.

I've tried to explain you each action I did>

Holoda at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 7
Hi Holod.............Thanks a lotIts working perfectly now, thanks for your yseful time devoted
singhvisuna at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 8
It's my pleasure!Sometimes Rodney and camickr help me very much, so I try to help other starters like I am too!
Holoda at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 9

Hi Holod,

Although this solution will work, it's not a good one.

You create 2 new models every time you want to move one element from one list to the other.

And then you copy all the elements to the new models.

This is completely unnecessary.

As I tried to explain, if you create the jlist from the beginning using DefaultListModel, you can just take the model from both lists and remove the selected element from the first list and add it to the second list.

Rodney_McKaya at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...
# 10

jList1 = new JList(new DefaultListModel());

That does not work....

The same... I do a project with JTable.

JTable is created with help of GUI Builder.

I try to do pretty the same:

1.Create my own model and reCreate JTable

2.put it in container instead of previous one

The idea of discussed task is the same.

modelWord = new DefaultTableModel(vectorWord,columnNamesUserVector);

modelWord.addTableModelListener(this);

jTableWord = new JTable(modelWord)

{

public Class getColumnClass(int column){

if(column == 0)

return Integer.class;

else

return getValueAt(0, column).getClass();

}//Class getColumnClass

//bla-bla-bla

//...

//..

};//table model

jScrollPane1.removeAll();

jScrollPane1.add(jTableWord);

Nothing happens:

No errors, no exceptions,

I see table which was built with help of GUI Buider.

newly created table doesn't appear

The same situation with your example....

No error, but nothing happens.

I don't know why...(((((

Holoda at 2007-7-12 21:39:45 > top of Java-index,Desktop,Core GUI APIs...