I want to get a result set with 2 fields from my DB.
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
And then I want to show the field called "name_prov" in the comboBox (As the item). But I also want to have my "id_prov" which is the ID (PRIMARY KEY) as the value for this item. This serves for the purpose of relating the name (of the providers in this case) with its ID just by using the combobox.
This is the code of the JComboBox event FocusGained that Im currently using.
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
CBProvedores.addItem(rs.getString("name_prov"));
//Here should be the Value related to the item I am creating
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
Is there anyway I can accomplish this?
First create a POJO, which will hold both your name and id.
public class ComboItem {
private String id;
private String name;
public ComboItem(String id, String name) {
this.id = id;
this.name = name;
}
// Add the getter and setter as you want.
// This will be used internally by JComboBox as the label to be displayed.
#Override
public String toString() {
return name;
}
}
Then use this POJO objects to be put into your JComboBox.
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
String id = rs.getString("id_prov"); // Get the Id
String name = rs.getString("name_prov"); // Get the Name
ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
CBProv.addItem(comboItem); // Put it into the ComboBox
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
And then finally to get the value selected, you can do this:-
CBProv.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ComboItem comboItem = (ComboItem) CBProv.getSelectedItem();
// comboItem.getId(), comboItem.getName() - Use as you wish.
}
});
Hi there i am Also still a newbie to java and javafx. This is what i did in javafx and it worked for me Hope you can work around it in java.
private void fillProviders()
{
List<String> providerList = new ArrayList<String>();
try
{
String Sql = "select * from prov ";
pat= conn.prepareStatement(Sql);
rs=pat.executeQuery();
while (rs.next())
{
providerList.add(rs.getString("id_prov")+" "+ rs.getString("name_prov"));
}
ObservableList<String> provider = FXCollections.observableArrayList(providerList);
bankName.setItems(provider);
}
catch( Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Hope it works for you. Note that my my combobox Name is bankName
Related
I m trying to override my JComboBox getSelectedItem method using this static method :
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
// query to select ID and TITLE from profiles table
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
ArrayList visualItems = new ArrayList(); // the Items of my combobox [item1,item2]
ArrayList idItems = new ArrayList(); // the corresponding IDs for each item [id1,id2]
while (myJComboResultSet.next()) {
visualItems.add(myJComboResultSet.getObject("TITRE")); // filling items set
idItems.add(myJComboResultSet.getObject("ID")); // filling IDs set
}
System.out.println("IDItems=" + idItems); // checking that my Items are filled
System.out.println("visualItems=" + visualItems); // checking that my IDs are filled
// creating a combobox of previous items
jComboBox = new JComboBox(visualItems.toArray()) {
ArrayList values = idItems;
// overriding the getSelectedItem to return the corresponding selected item's ID
#Override
public Object getSelectedItem() {
Object get = values.get(super.getSelectedIndex());
System.out.println("get = " + get);
return get;
}
};
}
I m calling this method from another frame :
JComboBoxTools.setupID_TITLE_ComboBox(J_Users_Profile,"profiles");
But when executed it don't work.
the output :
visualItems=[Admin,Teacher,Student]
IDItems=[0,3,5]
the selected item return value is : Teacher
Don't know what to do I want it to return 3 wich is the ID of teacher.
the full project is under : this link
thank you.
I get my desired values using a mapComboBoxModel
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
HashMap myMap = new HashMap();
while (myJComboResultSet.next()) {
myMap.put(myJComboResultSet.getObject("TITRE"), myJComboResultSet.getObject("ID"));
}
jComboBox.setModel(new MapComboBoxModel(myMap) {
#Override
public Object getValue(Object selectedItem) {
return map_data.get(selectedItem); //To change body of generated methods, choose Tools | Templates.
}
});
}
I overrided getValue to return the ID .
if (myComponent instanceof JComboBox) {
JComboBox jComboBox = (JComboBox) myComponent;
MapComboBoxModel model = (MapComboBoxModel) jComboBox.getModel();
values+=""+model.getValue(model.getSelectedItem())+",";
}
If I have a class with prepared statements, how do I call them when a user presses a button.
class updateeButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
name = displayName.getText();
price = bookPrice.getText();
Queries update = new Queries();???????????????????
}
}
Prepared Statement in different class
public int update(String price, String name) throws SQLException {
ps2.setString(1, name);
ps2.setString(2, price);
System.out.print("Update - ");
return ps2.executeUpdate();
}
Create an object and invoke the update method with parameters as shown below:
public void actionPerformed(ActionEvent e) {
name = displayName.getText();
price = bookPrice.getText();
Queries update = new Queries();
update.update(price, name);//invoke the method using the object
}
context :
i'm working on an applet witch manage fidelity cards. past version of the app had been done by an other developper. there is no documentation. i have to improve it.
problem :
to reach a customer, the app have some combobox. those combobox are filled by vertors
i try to sort item in the combobox but fail each times
i've read things about Collections.sort(x); where x could be a List or a Vector
but wherever i put the instruction for sorting elements, eclipse mark sort with this error :
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (Vector<NomClient>). The inferred type NomClient is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>
here is the code of the combobox :
private JComboBox<Object> getComboBox() {
if (this.comboBox == null) {
this.comboBox = new JComboBox<Object>();
this.comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
try {
SelectionNumeroCarteFidelite2.this.name = SelectionNumeroCarteFidelite2.this.comboBox
.getSelectedItem().toString();
SelectionNumeroCarteFidelite2.this.mod2 = new DefaultComboBoxModel<Object>(
Select.listePrenomclientfidelite(SelectionNumeroCarteFidelite2.this.name));
SelectionNumeroCarteFidelite2.this.comboBox_1
.setModel(SelectionNumeroCarteFidelite2.this.mod2);
SelectionNumeroCarteFidelite2.this.lblTaperOuSlectionner
.setVisible(false);
} catch (final Exception e1) {
final String message = "Choix Impossible - Merci de vérifier votre sélection";
System.out.print("Nom " + message);
final AlerteSelection fenetre = new AlerteSelection(
SelectionNumeroCarteFidelite2.this.interfaceactuelle,
message);
fenetre.setVisible(true);
SelectionNumeroCarteFidelite2.this.interfaceactuelle
.setEnabled(false);
SelectionNumeroCarteFidelite2.this.lblValider
.setVisible(false);
SelectionNumeroCarteFidelite2.this.lblTaperOuSlectionner
.setVisible(true);
}
}
});
this.comboBox.setEnabled(false);
this.comboBox.setForeground(Color.GRAY);
this.comboBox.setFont(new Font("Tahoma", Font.BOLD, 11));
this.comboBox.setEditable(true);
this.comboBox.setBorder(null);
this.comboBox.setBackground(Color.WHITE);
this.comboBox.setBounds(528, 426, 278, 22);
this.mod = new DefaultComboBoxModel<Object>(
Select.listenomclientfidelite());
this.comboBox.setModel(this.mod);
AutoCompletion.enable(this.comboBox);
}
return this.comboBox;
}
here is the code of the Select.listenomclientfidelite()
public static Object[] listenomclientfidelite() {
final Vector<NomClient> requete = new Vector<NomClient>();
try {
c = Connexion.getCon();
final String sql = "SELECT DISTINCT NOMCLIENT FROM CARTE_DE_FIDELITE INNER JOIN CLIENT ON CLIENT.IDCLIENT=CARTE_DE_FIDELITE.IDCLIENT";
preStm = c.prepareStatement(sql);
rs = preStm.executeQuery();
} catch (final Exception e) {
System.out.print("erreur" + e.getMessage());
}
try {
requete.add(null);
NomClient liste;
while (rs.next()) {
liste = new NomClient();
liste.setNom(rs.getString(1));
requete.add(liste);
System.out.println("listenomclientfidelite, liste is : "+liste);
}
rs.close();
preStm.close();
} catch (final Exception e) {
System.out.print("errorlistenom" + e.getMessage());
}
return requete.toArray(new Object[0]);
After beeing advised by Hovercraft Full Of Eels to modify my class NomClient, i understood that my NomCli class was the problen and not the use of vector, so here is a new step but no solution yet , so here is my Modified NomClient Class :
public class NomClient implements Comparable<NomClient> {
String nom;
public String getNom() {
return this.nom;
}
public void setNom(final String nom) {
this.nom = nom;
}
#Override
public String toString() {
return this.nom;
}
#Override
public int compareTo(NomClient other) {
System.out.println("nom : "+this.nom);
System.out.println("nom to string : "+this.nom.toString());
System.out.println(other.nom);
System.out.println("compare to : "+other.nom.toString());
int last = this.nom.toString().compareTo(other.nom.toString());
return last == 0 ? this.nom.compareTo(other.nom) : last;
}
}
i also have added Collection sort just before the return statement in sselect.listenomclientfidelite(),
like this :
Collections.sort(requete);
return requete.toArray(new Object[0]);
Now i have to deal with a java.lang.NullPointerException. "other" is null
Does any one have a clue to properly sort my combobox ?
If you can't change the NomClient class so that it implements Comparable<NomClient>, meaning that you'd have to give it a public int compareTo(NomClient o) method, then use a Comparator<NomClient> in your sort method call. This is a class that you create that has one method, public int compare(NomClient o1, NomClient o2), and that returns a -1, 0, or 1, depending on if o1 is functionally less than, equal to or greater than the o2 parameter. You would pass your Comparator instance as the 2nd paramter in your Collections.sort(myCollection, myComparator) method call.
Note that your problem has nothing to do with use of a Vector, and all to do with the NomClient class not implementing Comparable.
thank to Hovercraft Full Of Eels his solution was the good one.
i realised the first item of my vector was null it's why the comparable methode failed. so i worked around to handle this case, and here are the final implementation :
for NomClient.java :
public class NomClient implements Comparable<NomClient> {
String nom;
public String getNom() {
return this.nom;
}
public void setNom(final String nom) {
this.nom = nom;
}
#Override
public String toString() {
return this.nom;
}
#Override
public int compareTo(NomClient other) {
// compareTo should return < 0 if this is supposed to be
// less than other, > 0 if this is supposed to be greater than
// other and 0 if they are supposed to be equal
int last = 10;
if (other != null){
last = -10;
if (this.nom != null){
last = this.nom.compareTo(other.nom);
}
}
return last;
for Select.listenomclientfidelite()
public static Object[] listenomclientfidelite() {
final Vector<NomClient> requete = new Vector<NomClient>();
try {
c = Connexion.getCon();
final String sql = "SELECT DISTINCT NOMCLIENT FROM CARTE_DE_FIDELITE INNER JOIN CLIENT ON CLIENT.IDCLIENT=CARTE_DE_FIDELITE.IDCLIENT";
preStm = c.prepareStatement(sql);
rs = preStm.executeQuery();
} catch (final Exception e) {
System.out.print("erreur" + e.getMessage());
}
try {
requete.add(null);
NomClient liste;
while (rs.next()) {
liste = new NomClient();
liste.setNom(rs.getString(1));
requete.add(liste);
System.out.println("listenomclientfidelite, liste is : "+liste);
}
rs.close();
preStm.close();
} catch (final Exception e) {
System.out.print("errorlistenom" + e.getMessage());
}
Collections.sort(requete);
return requete.toArray(new Object[0]);
}
nothing else to do than insert the returned ArrayList in a combobox.
I am using a simply city SuggestBox where I am getting list of cities from the database and putting them in GWT suggestBox oracle.
After that user can select his city from the suggestBox suggestions and user saves his record. For example, he will select "London" from the suggestbox list.
Now when user saves his record, I will not save "London" in the database for that user, instead I want to save "3" (london ID) in database.
For this what I am doing is like this:
public MultiWordSuggestOracle createCitiesOracle(ArrayList<City> cities){
for(int i=0; i<cities.size(); i++){
oracle.add(cities.get(i).getCity()+","+cities.get(i).getCityId());
}
return oracle;
}
Now, I have the city and cityID both displaying in suggestBox and then can save from there 'city' and 'cityId'.
Everything works fine, but it doesn't looks good:
like it dispays as "London,3" and so on in the suggestBox suggestions..
I don't want to show this 3, how and where can I save this Id(3) for future use?
You can also create your own typed Suggestion-Box. You need to implement "Suggestion" and extend "SuggestOracle".
Super simple version may look:
// CityOracle
public class CityOracle extends SuggestOracle {
Collection<CitySuggestion> collection;
public CityOracle(Collection<CitySuggestion> collection) {
this.collection = collection;
}
#Override
public void requestSuggestions(Request request, Callback callback) {
final Response response = new Response();
response.setSuggestions(collection);
callback.onSuggestionsReady(request, response);
}
}
//CitySuggestion
public class CitySuggestion implements Suggestion, Serializable, IsSerializable {
City value;
public CitySuggestion(City value) {
this.value = value;
}
#Override
public String getDisplayString() {
return value.getName();
}
#Override
public String getReplacementString() {
return value.getName();
}
public City getCity() {
return value;
}
}
// Usage in your code:
// list of cities - you may take it from the server
List<City> cities = new ArrayList<City>();
cities.add(new City(1l, "London"));
cities.add(new City(2l, "Berlin"));
cities.add(new City(3l, "Cracow"));
// revert cities into city-suggestions
Collection<CitySuggestion> citySuggestions = new ArrayList<CitySuggestion>();
for (City city : cities) {
citySuggestions.add(new CitySuggestion(city));
}
//initialize city-oracle
CityOracle oracle = new CityOracle(citySuggestions);
// create suggestbox providing city-oracle
SuggestBox citySuggest = new SuggestBox(oracle);
// now when selecting an element from the list, the CitySuggest object will be returned. This object contains not only a string value but also represents selected city
citySuggest.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
Suggestion selectedItem = event.getSelectedItem();
//cast returned suggestion
CitySuggestion selectedCitySuggestion = (CitySuggestion) selectedItem;
City city = selectedCitySuggestion.getCity();
Long id = city.getId();
}
});
Keep the reference from city name to id in a Map<String, Integer> and then look the ID up there before you save it.
I've an array keeping a list of Group objects. I want to set this list to the DropDownChoice component. However I want to show the end user only the name attribute of Group objects, and then get the selected values' id attribute to add database. What to do?
private List<Group> groupTypes;
DatabaseApp db = new DatabaseApp();
groupTypes = db.getGroups();
groupDropDownChoice = new DropDownChoice("type", groupTypes);
...
...
addUserForm.add(new Button("submit"){
#Override
public void onSubmit(){
Group group = (Group) groupDropDownChoice.getModelObject();
...
...
db.addUser(group.getId(), den, name, login, email, password1);
DatabaseApp.java
public List<Group> getGroups() throws SQLException{
List<Group> groups = new ArrayList<Group>();
try {
String query = "SELECT * FROM [GROUP]";
Statement statement = db.createStatement();
ResultSet result = statement.executeQuery(query);
while(result.next()){
int id = result.getInt("ID");
String name = result.getString("NAME");
groups.add(new Group(id, name));
}
result.close();
} catch (SQLException ex) {
throw new SQLException(ex.getMessage());
}
return groups;
}
DropDownChoice has another constructor accepting an additional parameter of an IChoiceRenderer that allows control of what's displayed and what's sent back with the form.
See this example.
In your code, an implementation could look approximately like
private List<Group> groupTypes;
DatabaseApp db = new DatabaseApp();
groupTypes = db.getGroups();
groupDropDownChoice = new DropDownChoice("type", groupTypes, new IChoiceRenderer(){
#Override
public Object getDisplayValue(Object object) {
return ((Group) object).getName();
}
#Override
public String getIdValue(Object object, int index) {
return Integer.toString(index);
}
});
...
...
addUserForm.add(new Button("submit"){
#Override
public void onSubmit(){
Group group = (Group) groupDropDownChoice.getModelObject();
...
...
db.addUser(group.getId(), den, name, login, email, password1);
You're just creating the DropDownChoice directly from the list of groups. It seems to me that what you really want is a model for the list of groups; see the IModel documentation. Then you can create a custom model that returns only the name of a group instead of the whole Group object.