How do I populate a JComboBox with an ArrayList? - java

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());

Related

ArrayList<String[]> won't add more than one item

I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData;
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData = new ArrayList<String[]>();
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!
you clear out foodData every time you call createFood remove this line:
foodData = new ArrayList();
and move the initialization to a static level , like this:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData = new ArrayList<String[]>();
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
Every time you call createFood(String[] foodArray) you create a new List instead of just adding the incoming item to the existing list.
Create the ArrayList in a different place and remove the line from the createFood method and it should work fine.
Worked like a charm. Man I don't know how I missed that... I guess when you look at the same problem for too long you miss the obvious. Thanks guys!

How to link elements of two linked list in java?

This is my starting code for a van rental database.
List<String> manual = new LinkedList<>();
List<String> automatic = new LinkedList<>();
List<String> location = new LinkedList<>();
manual.add("Queen");
manual.add("Purple");
manual.add("Hendrix");
automatic.add("Wicked");
automatic.add("Zeppelin");
automatic.add("Floyd");
automatic.add("Ramones");
automatic.add("Nirvana");
location.add("CBD");
location.add("Penrith");
location.add("Ceremorne");
location.add("Sutherland");
How can I link the cars to the location.
For example, location CBD has Wicked,Zepplin and Floyd, and Penrith has Queen.
So if the command line arguement has "Print CBD" then it must show the vans available in CBD.
Any help will be appreciated.
This is hardly a database. They are just three separate data pieces. Use some object-oriented design technique to create classes, such as a class called Van. For example, it's not java code exactly, just for example.
Class Van {
string name;
VanType type; // e.x, Enum {auto, manual}
Location location; // another class
}
I think you would be better off using the approach explained In This Post. I believe this would be a much clearer implementation.
I hope this helps.
Ok thats the code.
We are using only linked list as you wanted.
(linked list keeps track on the input order so we are using that too)
As it is one to many relation we should have some kind of "foreign key" so we can see the related object. For each car you add no matter manual or auto, you should add a key for the location as you can see below
for example rels[0] = 3; means that your first car will have relation with 4th object of the locations list. thats implemented in the code - take a look.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
List<String> manual = new LinkedList<String>();
List<String> automatic = new LinkedList<String>();
List<String> location = new LinkedList<String>();
int[] rels = new int[8];
//cars with relations
rels[0] = 1;
manual.add("Queen");
rels[1] = 1;
manual.add("Purple");
rels[2] = 1;
manual.add("Hendrix");
rels[3] = 1;
automatic.add("Wicked");
rels[4] = 0;
automatic.add("Zeppelin");
rels[5] = 0;
automatic.add("Floyd");
rels[6] = 1;
automatic.add("Ramones");
rels[7] = 2;
automatic.add("Nirvana");
//key-0
location.add("CBD");
//key-1
location.add("Penrith");
//key-2
location.add("Ceremorne");
//key-3
location.add("Sutherland");
//here is the value that you have from your input args[] for example
String desiredLocation = "CBD";
int index = getLocationIndex(location, desiredLocation);
//if desired location not found we will print nothing
if(index==-1)return;
List mergedCars = new LinkedList<String>();
mergedCars.addAll(manual);
mergedCars.addAll(automatic);
for (int i = 0; i < rels.length; i++) {
if(index == rels[i])
{
System.out.println(mergedCars.get(i));
}
}
}
private static int getLocationIndex(List<String> location, String desiredLocation) {
int counter=0;
for (Iterator iterator = location.iterator(); iterator.hasNext();) {
String temp = (String) iterator.next();
if(temp.equals(desiredLocation))
{
return counter;
}
counter++;
}
return -1;
}
}

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

Put JTextComponent and JComboBox in JTable

I have List and List and I need to create JTable with theese two columns. I am confused with model, can anybofy show me how to do that please, I am new to swing and Java ?
Please check out my answer to some other question. Where I have presented a simple table model often use.
In your case you would create data in a following way:
//I assumed here list 1 and 2 have the same sizes
List<Object> list1 = getList1();
List<Object> list2 = getList2();
int rNo = list1.size();
List<List<Object>> data = new ArrayList<List<Object>>(rNo);
int cNo = 2;
for(int i = 0; i < rNo; i++)
{
List<Object> r = new ArrayList<Object>(cNo);
r.add(list1.get(i));
r.add(list2.get(i));
data.add(r);
}
tm.setData(data);
No worries, just set your desired component as a cell editor for that column. Simple ain't it.
Example Snippet
public class JTextFieldCellEditor extends DefaultCellEditor {
JTextField textField;
public JTextFieldCellEditor() {
super(new JTextField());
textField = (JTextField) getComponent();
}
}
Then include it like below,
TableColumn column = myTable.getColumnModel().getColumn(0);
column.setCellEditor(new JTextFieldCellEditor());
Further reading:
Here is your best bet, Swing tutorial for JTable.

Categories

Resources