Shuffle DefaultListModel - java

Is there a quickest way to shuffle the items of a DefaultListModel other than copying all elements in a separate arraylist, I'm using the code below, but it gives me a java.lang.ClassCastException :
....
private DefaultListModel<String> listModel = new DefaultListModel<String>();
...
Collections.shuffle((List<?>) listModel, new java.util.Random(seed));
...
Any suggestion

Not completely sure of the indices but something like this:
private DefaultListModel<String> listModel = new DefaultListModel<String>();
...
static void shuffle(DefaultListModel<String> mdl){
for(int i=0;i<mdl.size();i++){
int swapWith = (int)(Math.random()*(mdl.size()-i))+i;
if(swapWith==i) continue;
mdl.add(i, mdl.remove(swapWith));
mdl.add(swapWith, mdl.remove(i+1));
}
}

Related

javax.swing.JList<String> don't refresh with Apache Cassandra data

I'm trying to display data from a Apache Cassandra database. I have this code:
private void jButtonTimelineActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
List<Row> l = cassandra.queryTimeline();
JList<String> listaTweets= new JList<String>();
for(Row r : l) {
JLabel label = new JLabel(r.getString(3));
System.out.println(r.getString(3));
jList1.add(label);
}
jList1.revalidate();
jList1.repaint();
}
I have tried many things and the UI don't display the labels. I'm sure that the list of Rows is correct. What can I do?
You have post an unfinished code. its hard to to understand thses type of code. though i have something in my mind. hope this works.
DefaultListModel<String> model = new DefaultListModel<>();
JList<String> jList1 = new JList<>( model );
now add those items to "model" like this
model.addElement(lavel.getString());
no need to add these codes jList1.revalidate();
jList1.repaint();

Unable to fetch value from ArrayList saved in an object , and object saved in a HashMap

I am working on Swing and I am unable to fetch the value from arrayList saved in an object , which is then saved in a hashMap.
system.out.println prints no values.
My code contains a procedure list, and a parameter list.
After clicking on the add parameter button the parameters get added to paramList
When add procedure button is clicked the procedure fetched from textfield is saved in procList.
Values from paramList are saved in new Object (object contains arraylist with getters and setters)
The Hashmap stores the procedure name as key and the object as value
Then, I have another event, where we click on procedure List on GUI, then we fetch the selected procedure name,
That selected procedure name can be used as Key to fetch value from the HashMap.
we get the array list of parameters from hashmap using the key.
But when i tried to display in the GUI then it was blank, Then i tried to see if values are there using System.out.println and no value from printed :-(
The issue is with private void getParameterList
here is the code.
//variable declaration
String procedureName;
String parameterName;
ArrayList<String> procList = new ArrayList<>();
ArrayList<String> paramList = new ArrayList<>();
HashMap<String,ParamListPojo> procMapper = new HashMap<>();
private void Button_addParameterActionPerformed(java.awt.event.ActionEvent evt) {
parameterName = paramField.getText();
paramList.add(parameterName);
//System.out.println(paramList);
DefaultListModel paramListModel = new DefaultListModel();
//populating DefaultListModel for parameters
Iterator<String> it2 = paramList.iterator();
while(it2.hasNext()){
paramListModel.addElement(it2.next());
}
//populating parameterList
parameterList.setModel(paramListModel);
paramField.setText("");
}
private void button_addProcedureActionPerformed(java.awt.event.ActionEvent evt) {
//procedureName = level_funcPrefix.getText() +procedureField.getText();
ParamListPojo paramListPojo = new ParamListPojo();
procList.add(procedureName);
//Storing procedures and parameters in MAP
paramListPojo.setParamList(paramList);
procMapper.put(procedureName,paramListPojo);
System.out.println(procList);
System.out.println(paramList);
System.out.println(procMapper);
procedureField.setText("");
DefaultListModel procListModel = new DefaultListModel();
DefaultListModel paramListModel = new DefaultListModel();
// populating DefaultListModel for procedureList
Iterator<String> it1 = procList.iterator();
while(it1.hasNext()){
procListModel.addElement(it1.next());
}
//populating DefaultListModel for parameters
Iterator<String> it2 = paramList.iterator();
while(it2.hasNext()){
paramListModel.addElement(it2.next());
}
// populating procedureList
procedureList.setModel(procListModel);
procedureList.setSelectedIndex(procList.size()-1);
//populating parameterList
parameterList.setModel(paramListModel);
paramList.clear();
}
// populate Parameter List on GUI when procedure is selected
private void getParameterList(java.awt.event.MouseEvent evt) {
String procedure = procedureList.getSelectedValue();
System.out.println("MouseClickEvent , procedure is "+procedure);
//ParamListPojo prjL = new ParamListPojo();
ParamListPojo prjL = procMapper.get(procedure);
paramList = prjL.getParamList();
System.out.println(paramList);
//Declaring DefaultListModel for parameters
DefaultListModel paramListModel = new DefaultListModel();
Iterator<String> it = paramList.iterator();
while(it.hasNext()){
String parameter = it.next();
paramListModel.addElement(parameter);
System.out.println(parameter);
}
The console output is
[p_csacas]
[scasca, ascacasc, ascacs]
{p_csacas=wrapperbuilder.ParamListPojo#1150594}
[p_csacas, f_ascasc]
[rrrrrr]
{p_csacas=wrapperbuilder.ParamListPojo#1150594, f_ascasc=wrapperbuilder.ParamListPojo#26df23}
MouseClickEvent , procedure is p_csacas
[]
So we can see while adding procedure the values are there in both list, ans also in the HashMAP
But while fetching on mouse click on list in GUI , the output is coming blank.
Sample image of GUI is as given
Please help me with this :-(
The problem is solved.
The issue was with the setter method of arrayList in ParamListPojo class.
public void setParamList(ArrayList<String> procList) {
//this.prmList = procList;
prmList.addAll(procList);
}
previously i was using the this.prmList = procList
now i am using prmList.addAll(procList);

Java ArrayList search element and input into Jlist

I want to program a search function of the arraylist . Example I search for Simon, name that contains Simon should show up in the Jlist as shown below. The part I couldnt figure is what is the condition should I check for and what should I be adding.
Screenshot
Main
public static ArrayList al = new ArrayList();
al.add("Alica Wonderland");
al.add("Bob Jr");
al.add("Simon Tay");
al.add("Simon Corbell");
al.add("Simon Flyman");
al.add("Simon Jr");
al.add("David Copper");
Button Action
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
String value = txtSearch.getText();
listModel = new DefaultListModel();
JList ListAll = new JList(listModel);
if(al.contains(value)){
listModel.addElement(?Name that contains Simon?);
}
ListAll.setModel(listModel);
}
You could iterate over ArrayList elements:
for (Object s : al) {
if (((String)s).contains("Simon"))
listModel.addElement(s);
}
PS: You can avoid cast stuff by defining a type for ArrayList:
List<String> al = new ArrayList<String>();
Try this:
for(int i=0;i<al.size();i++)
if(al.get(i).contains(value))
listModel.addElement(al.get(i));
I think you mean something like this:
String name = "Simon";
for(int k = 0; k = yourArraylist.size() - 1; k++) {
if(yourArraylist.get(k).equals(name)) {.
your_Jlist.add(name);
//...
}
}

How to add element to existing JList

Part of my code
ArrayList<Item> i = g.getItems();
Vector itemsVector = new Vector(i);
JList items = new JList(iemsVector);
Later in the code I create new object which I want to add to JList. How can I do that?
Populate the JList with a DefaultListModel, not a vector, and have the model visible in the class. Then simply call addElement on the list model to add items to it.
Well you can not use directly that Array but use this this will might help you for the same.
DefaultListModel demoList = new DefaultListModel();
demoList.addElement("addElements");
JList listd = new JList(demoList);
That way you can add elemets into the LIST.
You may add it (new object) to the itemsVector (Vector). After adding an item into Vector object invoke the items.setListData(itemsVector); method.
Try with the add method, like this: items.add(newItem).
private javax.swing.JList<String> list1;
list1.setFont(new java.awt.Font("Tahoma", 0, 24));
DefaultListModel listModel1 = new DefaultListModel();
String st="Working hard";
listModel1.addElement(r);
list1.setModel(listModel1);
I'm using code similar to the following:
public void addRow(MyObject object)
{
Object[] objects = new Object[]{object.getSomeInt(), object.getSomeString()};
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
tableModel.addRow(objects);
}
Try this:
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
// Initialize the list with items
String[] items = { "A", "B", "C", "D" };
for (int i = 0; i < items.length; i++) {
model.add(i, items[i]);
}
source : java2s

How do I populate a JComboBox with an ArrayList?

I need to populate a JComboBox with an ArrayList. Is there any way to do this?
Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox
See the JavaDoc and tutorial for more info.
Elegant way to fill combo box with an array list :
List<String> ls = new ArrayList<String>();
jComboBox.setModel(new DefaultComboBoxModel<String>(ls.toArray(new String[0])));
I don't like the accepted answer or #fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.
String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);
Alternatively, you can also maintain strong typing by just using a for loop.
String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);
DefaultComboBoxModel dml= new DefaultComboBoxModel();
for (int i = 0; i < <ArrayList>.size(); i++) {
dml.addElement(<ArrayList>.get(i).getField());
}
<ComboBoxName>.setModel(dml);
Understandable code.Edit<> with type as required.
I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.
JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));
my example is only strings though.
Check this simple code
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class FirstFrame extends JFrame{
static JComboBox<ArrayList> mycombo;
FirstFrame()
{
this.setSize(600,500);
this.setTitle("My combo");
this.setLayout(null);
ArrayList<String> names=new ArrayList<String>();
names.add("jessy");
names.add("albert");
names.add("grace");
mycombo=new JComboBox(names.toArray());
mycombo.setBounds(60,32,200,50);
this.add(mycombo);
this.setVisible(true); // window visible
}
public static void main(String[] args) {
FirstFrame frame=new FirstFrame();
}
}
By combining existing answers (this one and this one) the proper type safe way to add an ArrayList to a JComboBox is the following:
private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
In your GUI code you set the entire list into your JComboBox as follows:
DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);
i think that is the solution
ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String hql = "FROM table ";
org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();
cat.getLibCat();//table colonm getter
combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());

Categories

Resources