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);
//...
}
}
Related
Sorry to repeat the question but i am new and looking the others answers didn't help me much.
I'd like to update my arraylist but i get stuck in an error that i cannot solve. Eclipse underlines the word set.
My code is:
private List<List> lists;
public void updateList(int index, string a) throws listException {
for(index = 0; index<list.size(); index++) {
list.get(index);
list.set(index, a);
}
You named the list as lists and trying to access list in the for-loop.
So your for loop should become like this:
for(index = 0; index<lists.size(); index++) {
lists.get(index);
lists.set(index, a);
}
Also it's String and not string and you will have to initialize the list.
So first change:
// Type should be String
private List<String> lists = new ArrayList<>();
And am not sure what is listException.
public void updateList(int index, String a) {
// Your rest of the code.
I made a List in java as under:
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList places = new JList(names) ;
Then in order to access the selected values I wrote in valueChanged method :
String[] emailID= places.getSelectedValuesList().toString[];
which is coming out to be incorrect ... Kindly help how should I rewrite this line so as the selected values get stored in array.
If you want to have all selected Items as an Array you can do something like this:
public static void main(String[] args){
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList<String> places = new JList<String>(names) ;
places.setSelectedIndices(new int[]{0,1,2});
String[] emailIDs = places.getSelectedValuesList().toArray(new String[]{});
for(String s : emailIDs){
System.out.println(s);
}
}
Note:
I added <String> to the List, because I assume you always want to have Strings as values. That way you can get the List .toArray() method with a generic output. Else you'd need to get an Object[] (Object Array) and cast the values.
For Storing Selected Items in String Array you can try this
Object[] values = places.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String newCD = (cdInput.getText());
List <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleG","ExampleB","ExampleR","ExampleX");
cdList.add(""+newCD);
List<String> sorted = new ArrayList<String>(cdList);
Collections.sort(sorted);
bigBox.setText("");
bigBox.append("Original Order\n**************\n");
for (String o : cdList) {
bigBox.append(o);
bigBox.append("\n");
}
bigBox.append("\n\nSorted Order\n************\n");
for (String s : sorted) {
bigBox.append(s);
bigBox.append("\n");
}
}
With this code, I can add 1 value, but when I try to add another one, it erases the original and replaces it. What can I do to prevent this?
PS. I'm trying to make a List of CDs, and be able to add new ones and have them also sorted and put in thier original order
Based on your code, you have no centralised instance of List, which means, each time you activate the button, it has no concept of what was previously in the list.
Start by creating an instance variable of the cd List and only add new items to it as required.
Something more like...
private List<String> cdList = new ArrayList<>(25);
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String newCD = (cdInput.getText());
cdList.add(newCD);
List<String> sorted = new ArrayList<String>(cdList);
Collections.sort(sorted);
bigBox.append("Original Order\n**************\n");
for (String o : cdList) {
bigBox.append(o);
bigBox.append("\n");
}
bigBox.append("\n\nSorted Order\n************\n");
for (String s : sorted) {
bigBox.append(s);
bigBox.append("\n");
}
}
I'm confused about on how to use this array in a way that is simple. Well I already passed the values from the JSON into a List and now I need to retrieve it using a loop (and just loop) but I don't know how. Tried reading some answers but I found myself really confused in the end. I just want it to be simple as making a String array, loop and fetch data by getting the variable[index] simple as that but all the answers I've found just lead me into confusion. Help please.
As I understand your question..
From Java List class you have to methods add(E e) and get(int position).
add(E e)
Appends the specified element to the end of this list (optional operation).
get(int index)
Returns the element at the specified position in this list.
Example:
List<String> myString = new ArrayList<String>();
// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");
// retrieving data from string list array in for loop
for (int i=0;i < myString.size();i++)
{
Log.i("Value of element "+i,myString.get(i));
}
But efficient way to iterate thru loop
for (String value : myString)
{
Log.i("Value of element ",value);
}
public static void main(String[] args) {
List<String> ls=new ArrayList<String>();
ls.add("1");
ls.add("2");
ls.add("3");
ls.add("4");
//Then you can use "foreache" loop to iterate.
for(String item:ls){
System.out.println(item);
}
}
Use the For-Each loop which came with Java 1.5, and it work on Types which are iterable.
ArrayList<String> data = new ArrayList<String>();
data.add("Vivek");
data.add("Vadodara");
data.add("Engineer");
data.add("Feelance");
for (String s : data){
System.out.prinln("Data of "+data.indexOf(s)+" "+s);
}
Try following if your looking for while loop implementation.
List<String> myString = new ArrayList<String>();
// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");
int i = 0;
while (i < myString.size()) {
System.out.println(myString.get(i));
i++;
}
List<String> al=new ArrayList<string>();
al.add("One");
al.add("Two");
al.add("Three");
for(String al1:al) //for each construct
{
System.out.println(al1);
}
O/p will be
One
Two
Three
Answer if you only want to use for each loop ..
for (WebElement s : options) {
int i = options.indexOf(s);
System.out.println(options.get(i).getText());
}
pst = con.createStatement();
ResultSet resultSet= pst.executeQuery(query);
String str1 = "<table>";
int i = 1;
while(resultSet.next()) {
str1+= "</tr><td>"+i+"</td>"+
"<td>"+resultSet.getString("first_name")+"</td>"+
"<td>"+resultSet.getString("last_name")+"</td>"+
"<td>"+resultSet.getString("email_id")+"</td>"+
"<td>"+resultSet.getString("dob") +"</td>"+
"</tr>";
i++;
}
str1 =str1+"<table>";
model.addAttribute("list",str1);
return "userlist"; //Sending to views .jsp
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());