I have a JList, where it displays names according to the DB. Associated with these names are IDs. for eg., foodId = 1, foodName = Chinese.
If i click on an item on the JList, i need to capture the foodID associated with the clicked foodName. i know a variable is needed.
when i have that value, I can pass that value into another method to retrieve the relevant food items associated with that foodId. Assume that getters & setters are done.
I have only the following, & am stuck. Please advise thank you.
list_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
//alter text of Label acc to clicked item # JList
JList list = (JList)evt.getSource();
System.out.println (list.getSelectedValue());
//store int value of item clicked # JList
int temp = 0;
temp = ???????????
//populate JPanel
Food food = new Food();
JPanel panel = new JPanel();
panel.setBounds(153, 74, 281, 269);
panel.add(food.populateWithButtons());
contentPane.add(panel);
}
});
list_1.setBorder(new LineBorder(new Color(0, 0, 0), 0));
//populate JList
list_1.setModel(food.populateJList());
public ListModel populateJList()
{
DefaultListModel model = new DefaultListModel();
ResultSet rs = null;
DataAccessObject db = new DataAccessObject();
db.setUp("customer");
String dbQuery = "SELECT store_Owner_Id, food_Category FROM store_owner";
rs = db.readRequest(dbQuery);
try
{
while (rs.next())
{
food_Category = rs.getString("food_Category");
store_Owner_Id = rs.getInt("store_Owner_Id");
model.addElement(food_Category);
System.out.println (store_Owner_Id); //test DB conn & print retrieved items
System.out.println (food_Category);
}
}
catch (Exception e)
{
e.printStackTrace();
}
db.terminate();
return model;
}
Suggestions:
Don't populate the JList with Strings but rather ...
If you populate your JList with objects that contain both the name and the ID, then you're doing well.
You will likely want to give your JList a cell renderer that helps it to show the information from the object that you want the JList to display.
Then getting the ID is simply a matter of getting the selected item from the JList inside whatever listener you're using, casting it to the object type that in fact is, and then calling the getter method, such as getId(), assuming that objects of this type have this method, and then use your ID.
Note though that this tells us nothing useful:
list_1.setModel(food.populateJList());
If my suggestions don't help you answer your question, then please provide more useful information and code, information that will help us to fully understand your problem.
Edit 2
Your latest code shows that you're doing what I recommended that you not do:
while (rs.next())
{
food_Category = rs.getString("food_Category");
store_Owner_Id = rs.getInt("store_Owner_Id");
model.addElement(food_Category); // ****** here
System.out.println (store_Owner_Id);
System.out.println (food_Category);
}
You're adding Strings to your DefaultListModel, and by doing this you lose all the other information that the database gave you.
Again do not add Strings to this model. Create a class that has two or more fields, one for the category String, and one for the owner ID, that has getters, setters, and a constructor that allows you to pass this information into objects of the class, create objects of this class in your while loop above, and add these to the JList model. Then give your JList a custom renderer which is better than giving the custom object a toString() method for this purpose.
Create a custom class, say called FoodInfo
Declare the DefaultListModel as one that accepts objects of this type, DefaultListModel<FoodInfo>
Then add objects of this type to the model:
e.g.,
DefaultListModel<FoodInfo> model = new DefaultListModel<FoodInfo>();
// ... other code to get database info
while (rs.next()) {
String foodCat = rs.getString("food_Category");
int id = rs.getInt("store_Owner_Id");
FoodInfo foodInfo = new FoodInfo(foodCat, id);
model.addElement(foodInfo);
}
Edit 3
As has been noted in comment by #dic19, don't use a MouseListener on the JList but rather use a ListSelectionListener as described in the JList Tutorial.
See Combo Box With Hidden Data. It will show you how to use a custom object without the need for a custom renderer. I know the title is "Combo Box" but the concept is identical for a JList.
When you use a custom renderer you break the default functionality of JList since you will no longer be able to select items using the keyboard. A properly designed GUI should allow the use to use the mouse or keyboard to select an item.
Related
i am stuck with a new problem, don't know if this works but here i have list of JCombobox as follow.
JCombobox comboBox = new JComboBox();
comboBox.addItem("UserName");
comboBox.addItem("Password");
comboBox.addItem("DLNo 20 b");
comboBox.addItem("DLNo 20 b");
i want to print my database column names which are more than 40!
when i select the Combobox it must internally print my custom item here.
Here i tried with this code but i am not satisfied with this
if(comboBox.getSelectedIndex()==0)
{
System.out.println("U_NAME");
}
if(comboBox.getSelectedIndex()==1)
{
System.out.println("P_NAME");
}
if(comboBox.getSelectedIndex()==2)
{
System.out.println("DL_NO_20_b");
}
if(comboBox.getSelectedIndex()==3)
{
System.out.println("DL_NO_20_b");
}
is there any better way to over come this, like mapping objects
You could create a class ComboBoxItem with a name- and a columnName-attribute.
Use instances of this class for the ComboBox.
In the ComboBoxItem-class, overwrite the toString()-method to return the name, so it gets displayed as wished in the ComboBox. Add a getColumnName()-method to return the columnName, so you could invoke getSelectedItem().getColumnName().
I use JcomboBox as a suggestion box that when user type in, it check for matches and display suggestion.
Here is how I create the JComboBox:
Vector<String> popUpVector = new Vector<String>();
JComboBox jcb = new JComboBox(popUpVector);
every time Key Listener catch event, I do this
popUpVector.clear();
jcb.hidhPopUp();
for(String s : database){
popUpVector.add(s);
}
jcb.showPopUp();
It works as long as I don't select item from the dropdown.
However, once I select item from the dropdown, the dropDown will display blank afterward, I check the popUpVector, it is not empty though, I think it has something to do with the selection, so I unhook it from actionListener, it didn't helps.
Can anyone help me with this, thanks a lot!
Passing a Vector to the JComboBox constructor will according to the source indeed use that vector to back the underlying model:
public JComboBox(Vector<?> items) {
super();
setModel(new DefaultComboBoxModel(items));
init();
}
and
public DefaultComboBoxModel(Vector<?> v) {
objects = v;
if ( getSize() > 0 ) {
selectedObject = getElementAt( 0 );
}
}
Meaning that if you change the contents of the vector, you also change the contents of your model. However, making changes to the model requires to fire the correct events to inform the view about the changes. And since vector does not fire any events, the DefaultComboBoxModel has no way of knowing that the contents of the vector has been changed.
So imo the DefaultComboBoxModel constructor simply should have taken the elements from the vector and store those iso storing the vector directly.
Now to solve your problem: instead of storing your values in a Vector, use a DefaultComboBoxModel and use the available API on that model to make the changes. Using the API will make sure the model fires the correct changes. See for example the implementation of the addElement method:
public void addElement(Object anObject) {
objects.addElement(anObject);
fireIntervalAdded(this,objects.size()-1, objects.size()-1);
if ( objects.size() == 1 && selectedObject == null && anObject != null ) {
setSelectedItem( anObject );
}
}
your issue is
popUpVector.clear();
correct way to clear the Vector is only
popUpVector = new Vector<String>();
better could be to add / remove / modify the JComboBoxes Items in ComboBoxModel
I have a JList which uses a DefaultListModel.
I then add values to the model which then appear in the JList. I have created a MouseListener which (when double clicked) allows the user to edit the current user number of that person they have selected.
I have checked that the actual object of that record is being changed, and it is. The only issue I'm having is getting the actual Jlist to update to show the new values of that object.
Snippets of the current code I have are:
Creating the JList and DefaultTableModel:
m = new DefaultListModel();
m.addListDataListener(this);
jl = new JList(m);
jl.addMouseListener(this);
Updating the object:
String sEditedNumber = JOptionPane.showInputDialog(this, "Edit number for " + name, number);
if (sEditedNumber != null) {
directory.update (name, sEditedNumber);
}
And (when jl is the JList and m is the DefaultTableModel):
public void contentsChanged(ListDataEvent arg0) {
jl.setModel(m);
}
Instead of setModel(), update your existing model using one of the DefaultListModel methods such as setElementAt(), which will fireContentsChanged() for you.
You need to call fireContentsChanged() on the ListModel.
You need to call DefaultListModel.fireContentsChanged(). But since this method is protected (I really wonder why), you can't do that directly. Instead, make a small subclass:
class MinoListModel<T> extends DefaultListModel<T>
{
public void update(int index)
{
fireContentsChanged(this, index, index);
}
}
Use it as your list model:
m = new MinoListModel<>();
jl = new JList(m);
After updating a user number, update the corresponding entry: m.update(theIndex);
Alternatively, if you don't want a subclass, you can just replace the JList element after the user number changed: m.setElementAt(theSameElement, theIndex);. Though this is somewhat cumbersome and having a subclass seems the cleaner approach.
I've created a database application with the NetBeans GUI-Designer.
GUI with Comboboxes (Bound to MySQL databasetables user and team):
on Button new -> jDialog - executes a query to store a new user in database:
Problem: Combobox is updated at the programstart but not while running the program.
Question: Is it possible to update the entries in my combobox directly when a new user or team is saved? And how could I Implement this?
Edit: Here is what I do when clicking on the saveButton in the JDialog:
int k=st.executeUpdate(
"INSERT INTO User (username) " + " VALUES ('"+ name + "')");
//Here I'd like to update the jComboBox1 directly if possible
Outerclass.jComboBox1...;
JOptionPane.showMessageDialog(null, "User is successfully saved");'
Just update your component's ComboBoxModel when you insert a new user in the database. If this is not helpful, please provide an sscce that exhibits the problem.
Addendum: Given a reference to a JComboBox,
private final JComboBox combo = new JComboBox();
you can update its model, as shown below. This example adds name to the beginning of the list, but SortedComboBoxModel is an appealing alternative.
DefaultComboBoxModel model = (DefaultComboBoxModel) combo.getModel();
model.insertElementAt(name, 0);
Addendum: More simply, use the method available to the combo itself,
combo.insertElementAt(name, 0);
I ran into a similar problem: if you enter anything into the database, that is supposed to be reflected in the JComboBox, then you can't change the values of that combo box. It would be great if you could add things to the JComboBox "on the fly" directly, but you have to get that data, create a new ComboBoxModel from it, and then set your JComboBox to that new model.
Here, I use DefaultComboBoxModel, which can either take an array of objects (usually strings) or a vector. If you use vectors to represent your underlying data model, that's a lot easier, since vectors are dynamic data structures.
My code:
Vector<String> s = new Vector<String>();
try {
// I'm using prepared statements, get the ResultSet however you like
ResultSet rs = myPreparedStatement.executeQuery();
while ( rs.next() ) {
// Change "1" to whatever column holds your data
s.add(rs.getString(1));
}
} catch (SQLException ex) {
ex.printStackTrace(); // or whatever
}
DefaultComboBoxModel jcbModel = new DefaultComboBoxModel(s);
jcb.setModel(jcbModel);
EDIT: Remember that ResultSet columns are 1-indexed, not 0-indexed! Gets me every time.
I am trying to search for UserName and return values onto jComboBox, here is the code
public void actionPerformed(java.awt.event.ActionEvent e) {
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
userList[i]= usrList.get(i).getUserName();
}
model = new DefaultComboBoxModel(userList);
jComboBoxReceiver.setModel(model);
}
after you click to somewhere else or click enter,it will conduct the search, however, it will go search for the first item again, which is very confusing... then i tried using key Pressed
if(e.getKeyCode()==13){
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
userList[i]= usrList.get(i).getUserName();
}
model = new DefaultComboBoxModel(userList);
jComboBoxReceiver.setModel(model);
}
And this one does not react at all.
You need to set the listener(s) on the Editor not the ComboBox itself. See the answer here:
Detecting when user presses enter in Java
Wow, you're rebuilding a ComboBoxModel each time ? Isn't it a little expensive ? You know there is a MutableComboBoxModel, also implemented by DefaultComboBoxModel that would allow you to add/remove elements from you combobox without rebuilding its model each time ?
Concerning your question, I don't understand the statement
However, if i do that, it does perform correctly, however, it will go search for the first item again
Do you mean your JComboBox starts to blink with content being modified each time ?
if so, maybe is it because your ActionListener is linked to JComboBox, which content changes continuously.
Anyway, i suggest you add some logs, like
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBoxReceiver.getModel();
model.remvoeAllElements();
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
String username = usrList.get(i).getUserName();
System.out.println(username); // feel free to instead use one loger
model.addElement(username);
}
Besides, i would tend to suggest you an other approach, in which combo box model don't contain simple Strings, but rather User objects, with a ListCellRenderer displaying only the user name.
IMO, what will really be confusing for your users is to have the content and selection of a combo box changed as soon as they select one of its options.
Anyway, if you really want to do that, then you should remove the action listener (or deactivate it) before changing its content, and re-add it (or reactivate it) after :
public void actionPerformed(java.awt.event.ActionEvent e) {
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
userList[i]= usrList.get(i).getUserName();
}
model = new DefaultComboBoxModel(userList);
jComboBoxReceiver.removeActionListener(this);
jComboBoxReceiver.setModel(model);
jComboBoxReceiver.addActionListener(this);
}