java - Moving selected data between two JList -
i trying develop java code move selected data between 2 jlist, getmodel() method not return defaultlistmodel , explicit casting not allowed list.getmodel() method, other possible way move selected data 1 other jlist , vice versa.?
here exact view of trying...("add all" , "remove all" buttons working well, using arralist that, finding solution selected data, includig ordering sequence of adding , removing data)
code:
for left jlist"
lmleft = new defaultlistmodel(); lstleft = new javax.swing.jlist(); lstleft.setmodel(lmleft);
for right jlist:
lmright = new defaultlistmodel(); lstright = new javax.swing.jlist(); lstright.setmodel(lmright);
solved : replaced jlist jtable
note : cannot cast defaultlistmodel getlist() return abstractlistmodel.
thank attention.
your solution should straight forward like:
- get selected items left list
- add selected items left list right list
and doing add , remove should without question simple. jlist class gives methods perform of above.
jlist.getselectedindices() return array of int (int[]) of indexes have been selected. go through list , take items @ indexes , add them right list.
list<object> myitemsforrightlist = new arraylist<object>(); int[] selectedindexes = jlistleft.getselectedindicies(); for(int i=0; < selectedindexes.length; i++) { object whatever = jlistleft.getelementat(selectedindexes[i]); ((defaultlistmodel)jlistright.getmodel()).addelement(whatever); }
i suggest @ api has offer @ http://docs.oracle.com/javase/6/docs/api/javax/swing/jlist.html
--- edit ---
because no complete source code provided, re-posting code above jdk 7 in mind
public static void main(string ... args) { jframe frame = new jframe("test"); frame.setdefaultcloseoperation(jframe.exit_on_close); defaultlistmodel<string> defaultlistmodel = new defaultlistmodel<string>(); defaultlistmodel.addelement("bla bla bla"); defaultlistmodel.addelement("ble ble ble"); defaultlistmodel.addelement("blo blo blo"); final jlist<string> list = new jlist<string>(); list.setpreferredsize(new dimension(400, 200)); list.setmodel(defaultlistmodel); jbutton button = new jbutton("add"); button.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { ((defaultlistmodel<string>)list.getmodel()).addelement("new 1 added"); } }); frame.setlayout(new borderlayout(5, 5)); frame.add(new jscrollpane(list), borderlayout.north); frame.add(button, borderlayout.south); frame.pack(); frame.setvisible(true); }
Comments
Post a Comment