How to bind an array to JComboBox dynamically? - java

I binding an array to JComboBox like following:
String[] arr={"ab","cd","ef"};
final JComboBox lstA = new JComboBox(arr);
but I want bind array to JComboBox dynamically like following :
final JComboBox lstA = new JComboBox();
void bind()
{
String[] arr={"ab","cd","ef"};
// bind arr to lstA
}
How to do it?

A little odd workaround(mine :)), might useful to you
final JComboBox lstA = new JComboBox();
String[] arr={"ab","cd","ef"};
lstA.setModel(new JComboBox(arr).getModel());

build your JComboBox with a dynamic ComboBoxModel
JComboBox(ComboBoxModel<E> aModel)
like http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultComboBoxModel.html
m=new DefaultComboBoxModel();
j=JComboBox(m);
you can then add and remove elements:
m.addElement("ab")
m.addElement("cd")
or, if you only need to put the array in the combox:
new JComboBox(new Sring[]{"ab","cd","ef"})

final JComboBox lstA = new JComboBox();
void bind()
{
String[] arr={"ab","cd","ef"};
// bind arr to lstA
lstA.setModel(new DefaultComboBoxModel<String>(arr));
}

Related

Use JList in JComboBox

I have a JList which is of DefaultListModel. I am not trying to create a JComboBox which should display as its the elements, the elements in the JList.
What is the best way to achieve this ?
Thank you.
My code:
DefaultListModel<String> listModelTopic = new DefaultListModel<>();
//create the list
listTopic = new JList<>(listModelTopic);
//create comboBox
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(topicList.getModel());
Error: The constructor DefaultComboBoxModel(ListModel) is undefined
Use copyInto on DefaultListModel to copy all the values to an array.
String[] lstArray = new String[listModelTopic.getSize];
listModelTopic.copyInto(lstArray );
Then create DefaultComboBoxModel using this array.
DefaultComboBoxModel comboModel = new DefaultComboBoxModel(lstArray );
JComboBox comboBox = new JComboBox();
comboBox.setModel(comboModel );
Hope this helps!

I have an ArrayList<JCheckBox> that i want to convert to an ArrayList<String>

I have an ArrayList<JCheckBox> that i want to convert to an ArrayList<String>
First I do like this. I get all my titles from a file and put them into a new ArrayList. Afterwords I make a new JCheckBox Array that contains all the Strings from the StringArray.
ArrayList<String> titler = new ArrayList<String>();
titler.addAll(FileToArray.getName());
ArrayList<JCheckBox> filmListe = new ArrayList<JCheckBox>();
for(String titel:titler){
filmListe.add(new JCheckBox(titel));
}
for(JCheckBox checkbox:filmListe){
CenterCenter.add(checkbox);
}
This is what I am trying to do: First I make a new ArrayList (still in the JCheckBox format), that contains alle the selected Checkboxes. Afterwords I want to add the to a new ArrayList in a String format.
The main problem is italicized (with **):
ArrayList<JCheckBox> selectedBoxes = new ArrayList<JCheckBox>();
for(JCheckBox checkbox: filmListe){
if (checkbox.isSelected()){
selectedBoxes.add(checkbox);
}
ArrayList<String> titlesArr = new ArrayList<String>();
for(JCheckBox titel:selectedBoxes){
*titlesArr.add(titel);*
}
A lot of code and text for a little problem! But I really appreciate your help! :)
You can't add a JCheckBox to a List<String>, the types JCheckBox and String are incompatibles.
I guess you want to add the text of the check box into your list, so you have to retrieve it manually, using:
titlesArr.add(titel.getText());
Assuming the checkbox's label is exactly the same as what you originally had in your list of titles, just use the checkbox's getText method (which gets the String label). You don't need to make a separate list of checkboxes that are checked - just put an if-block inside your first loop like this:
ArrayList<String> titlesArr = new ArrayList<String>(filmListe.size());
for (JCheckBox checkbox : filmListe) {
if (checkbox.isSelected()) {
titlesArr.add(checkbox.getText());
}
}
Try this:
ArrayList<String> titlesArr = new ArrayList<String>();
for(JCheckBox checkbox: filmListe)
if (checkbox.isSelected())
titlesArr.add(checkbox.getText());
Now titlesArr contains what you wanted.

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

java swing combobox

I have a combo box and a string array that holds all the values of the combo box in it. I erase the items from the combo box and then want to add in the values from the string array. It doesn't seem to let me just add in a string array. And I tried to itterate through the string adding items one by one but won't let me do that (or atleast the way I wrote it, it won't work).
May seem like a stupid question but I am new to working with swing in java.
Here's the code where I want to "reload" the items from the combo box:
String str = JOptionPane.showInputDialog(null, "Enter Name: ", "", 1);
if(str != null){
JOptionPane.showMessageDialog(null, "New name added: " + str, "", 1);
nameCreator.addName(strNames, str);
strNames = NameLoader.getNames();
nameList.removeAllItems();
nameList.addItem(strNames);
}
EDIT: Made small typo and didn't realize what was wrong. Working now. Thanks for everyones help.
Did you used the method addItem(Object anObject)?
You should iterate your array an use that method:
String[] data = {a;b;c;d;e}
for(int i=0; i < data.length; i++){
comboBox.addItem(data[i]);
}
Luca
I'd suggest you to implement your own ComboBoxModel:
public class YourComboBoxModel implements ComboBoxModel{
#Override
public Object getSelectedItem() {
//return selected item Object;
}
#Override
public void setSelectedItem(Object anItem) {
//set selected item
}
#Override
public Object getElementAt(int index) {
//return the element based on the index
}
#Override
public int getSize() {
//return the size of your combo box list
}
}
And build your JComboBox passing that model as parameter:
ComboBoxModel yourModel = new YourComboBoxModel();
JComboBox yourComboBox = new JComboBox(yourModel);
Using a custom ComboBoxModel is the most flexible solution. It allows you to change the datastructure holding your datas, and the way you access it, modifying only the model you implemented instead of other unrelated part of code.
Whenever you need to work with editable models for these kinds of GUI elements it is always good to use a model. For the JComboBox you have an easy-to-use DefaultComboBoxModel.
It works easily:
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[]{"Item1","Item2","Item3"});
JComboBox comboBox = new JComboBox(model);
in this way you have the model attached to the combobox, and it will display items from the array. Whenever you need to change them just do:
model.removeAllElements(); // if you need to empty it
model.addElement("New Item1");
model.addElement("New Item2");
model.addElement("New Item3");
model.fireContentsChanged();
and you'll have new items updated inside the GUI.
A bonus note: if you need to manage custom objects instead that strings you can easily add them to the JComboBox (in the sameway showed before), you just need to provide a custom public String toString() method that will manage the string representation.
In your example I don't get why you readd all the items everytime, you could just call addItem with the new String without removing everything and adding them back.
the best way to add some thing in your combo box in order that you can change it easily is to describe an array list first,if you would like to be dynamic you can user a text field then in a text field you can run an array list .
textField = new JTextField();
textField.setBounds(131, 52, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
then you have to create an array list
ArrayList al=new ArrayList();
then you have to equal your text field text to a string
String str=textfield.getText();
then add it to your array
al.add(str);
then add al item to your combo box.
JComboBox comboBox = new JComboBox();
comboBox.setBounds(112, 115, 145, 20);
contentPane.add(comboBox);
comboBox.addItem(al);

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