How can I put a index in a jcombobox in java? - java

I want to put in a jcombobox, the name and use the id for link the option select and the name.
I get the data of the db, but I don't know the way for add a items.
I try to write a item, with 2 parameters, but in the combobox appear the class name, not the value :
This is my code
rs = (ResultSet) stmt.executeQuery();
while ( rs.next() ) {
cbHabitaciones.addItem(new Item(rs.getInt("id"), rs.getString("tipo") +" - " +rs.getString("precio")));
}

Easiest way for you would be to override toString() method of the class which instances you are putting in the JCombo's model. That way you get your 'nice name' for each item. That class, of course, should contain everything you need for each item, e.g. id and name. On selection change, you can than use the id of the selected item.
If you cannot override 'toString()' or you want to separate objects you already have (e.g. if they are DTO) from the presentation objects, create your own class with only the things you need.
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String toString() {
return this.getName();
}
}

Related

date - name id conversion

Given (for example):
Dog breeds (Name)  | id
Labrador Retriever | A1
German Shepherd | A2
Golden Retriever | A3
Now the dog breeds are displayed in a list and someone can select one and i have to store the id from the selected dog.
The question is what is the best way to convert them in each other.
At the Moment in android i have two string array ressources, store in one the names and in the other the ids and have a method which searches for the name in the "name-array", give me the index and then i can get the id trough the second "id-array", because the id must be in the same index.
Thanks
Create a POJO (Plain Old Java Object) with two fields.
public class DogBreed {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Use custom adapter to show it. Then you don't have to worry about mirroring indices. Just use getter on correct object.
Default adapters usually use toString method. So you can use more generic solutions by overriding toString.
#Override
public String toString() {
return name;
}

Return an int value to Database

I am working on an application which makes it easier for employees to return lost luggage.
I'm working on a screen which registers a piece of luggage.
The status ComboBox is filled with data from the database, as well as the CustomerID combobox.
SCREEN:
http://gyazo.com/d81c7c2377c79eb2b42d6f101fb8d5f5
Now the ComboBox fetches an SQL query, and shows a firstname. But the customer has a customerID as well. For now i have a method which sets the value of the variable customerId, with:
lug.setCustomerID(String.valueOf(CustomerID.getSelectedItem()));
But then it sets its value to 'Khoa'.
How can i show a name in my combobox, but get the INT value of the customerID?
Instead of just adding strings to the ComboBox you can add an object with both ID and String.
You need to override the toString() function of your class from which you create the customer object.
public class Customer {
private String name;
private int id;
public Customer(String label, int identifier) {
name = label;
id = identifier;
}
public getId() { return id; }
#Overrider public String toString() { return name; }
}
You can when using an object out of that class
lug.setCustomerID(CustomerID.getSelectedItem().getId());
You should wrap your data in simple bean (e.g. Customer) with 2 fields: int id; String firstName and toString must return firstName.
After declare your combobox as JComboBox<Customer>.
The result will look like lug.setCustomerID(CustomerID.getSelectedItem().getId());

Get selected value JList or List in Java Swing, stuck with getElementAt() of ListModel

i am using Swing List control to bind data, I (must) use a class to make the model
public class SubjectListModel extends AbstractListModel<String> {
public ArrayList<Subject> listSubjects;
public SubjectListModel(ArrayList<Subject> listSubjects) {
this.listSubjects = listSubjects;
}
#Override
public int getSize() {
return listSubjects.size();
}
#Override
public String getElementAt(int index) {
return listSubjects.get(index).name;
}
class Subject{
int id;
string name;
}
I wish to use the List to bind my ArrayList, Can I set something like "display text field" for "name" field, and "value field" for my "id"? So that I can retrieve those values as needed.
The best dream is I can retrieve whole the selected "Subject" instead of a string field.
I seen the list only have getSelectedValue, and if I want to display the subject in the List, I must set getValueAt() in model to return the "name", and getSelectedValue() return the selected "name" too :( If I change getElementAt() in model class to return "Subject", the list will display #object.abxdef
Just override toString() of Subject, and return what ever you want to be displayed in the list. Then add all your Subject instances to the list. No need for a custom ListModel. Just use a DefaultListModel. When you get the selected Subject just use one of it's getters to the field you want.
Also no need to store your object in two locations, (i.e. the ListModel and the ArrayList) just add everything to the model.
class Subject {
private int id;
private String name;
public Subject(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public String getName() { return name; }
#Override
public String toString() {
return name;
}
}
DefaultListModel model = new DefaultListModel();
model.addElement(new Subject(1, "Math"));
Subject subject = (Subject)model.getElementAt(0);
System.out.println(subject);
// result -> Math

Java extracting individual data from an object list

I have a Java Class like this:
public class Employee {
String Name;
int Id;
int Age;
void setName(String tempVal) {
Name = tempVal;
System.out.println(Name);
System.out.println("\n");
}
void setId(int parseInt) {
Id = parseInt;
System.out.println(Id);
System.out.println("\n");
}
void setAge(int parseInt) {
Age = parseInt;
System.out.println(Age);
System.out.println("\n");
}
}
Now I want to parse a employees.xml file using SAXParser using the code in the link: http://totheriver.com/learn/xml/xmltutorial.html#5.2
The problem is when I am adding the tempEmp to the list and accessing the list to print its value in printData() method, the output is something like:
No of Employees '3'.
Employee#140de537
Employee#1c43882a
Employee#15a08be5
Now, how do I extract the name, age and id of the employee individually?
I guess you are adding the Employee object to the list and printing the objects directly from list.If you dont override the toString() method, it will call the toString() method of Object class(superclass of all class), which will be returing the classname#hashcode(hashcode of object).If you want to print some data from your class, you need to override toString() method in your class and return the format you require.
You have to implement a toString() method in the Employee class for it to be displayed correctly, something along these lines:
#Override
public String toString() {
return Id + " " + Name + " " + Age;
}
Also, remember that in Java attribute names should start with a lowercase character, not uppercase.
You want to add some getter methods.
You should also check out the code conventions for Java - some of your variables start with an uppercase letter where they should not.
To get each value individually, you need to add a few get methods
public String getName()
{
return Name;
}
public int getAge()
{
return Age;
}
public int getId()
{
return Id;
}

How to get unique id or value of every node in jtree?

I am new to jtree. I want to get the unique id or value of individual nodes which have same parent.
I tried with valuechanged() method, but i am able to get only the string value of every node.
I want to compare the current selecting node with some unique value of particular node. How can i achieve this?
I think i am making clear.
Is there any possibilites available?
Thanks in advance..
TreeNode has a getParent() method, you can compare the object reference returned with it with ==.
If you really need an unique id based on object identity, consider System.identityHashCode. See the following question:
How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?
I have been working on setting a unique Id for the DefaultMutableTreeNode. One method is to create a simple CustomUserObject Class which has tow properties, Id and Title. We can then assign the CustomUserObject instance as the Node UserObject property.
To make sure that only the Title is displayed in the Tree structure, override the toString() method in the CustomUserObject Class.
/* CustomUserObjectClass */
public class CustomUserObject implements Serializable {
private int Id = 0;
private String Title = null;
public CustomUserObject(int id, String title) {
this.Id = id;
this.Title = title;
}
public CustomUserObject() {
}
public int getId() {
return this.Id;
}
public String getTitle() {
return this.Title;
}
public void setId(int id) {
this.Id = id;
}
public void setSutTitle(String title) {
this.sutTitle = title;
}
#Override
public String toString() {
return this.Title;
}
Now to create a new node:
CustomUserObject uObj = new CustomUserObject(1, "My First Node");
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(uObj);
uObj = childNode.getUserObject();
uObj.getId();
uObj.getTitle();

Categories