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.
Related
I have a JTable which displays an Object[][] of data.
There is also a form on the same screen that lets the user add an item to the object to the list. Although for the life of me I can not get the list displayed in the table to update when the user presses the "Add Item" button.
(it gets appended to the array fine, and I can print it onto the screen, just can't get the table to change.)
Here is crating of the table
Object[] tableHeadings = {"Item Name","Qty/Weight","Price"};
ShoppingApplication shoppingApplication = new ShoppingApplication();
Object[][] tableData = shoppingApplication.generatePurchaseTableData();
final JTable tblBill = new JTable(tableData, tableHeadings);
Here is the table data being generated:
/**
* Generates data in the correct format to go into the table
* from the purchase list
* #return
*/
public Object[][] generatePurchaseTableData(){
Object[][] results = new Object[listOfPurchases.size()][2];
for (int i = 0; i<listOfPurchases.size(); i++){
Purchase purchase = listOfPurchases.get(i);
Object[] innerObject =
{purchase.getProductName(),
purchase.getPricePerUnit(),
purchase.getTotalPrice()};
results[i] = innerObject;
}
System.out.println(results.length);
return results;
}
}
Here's the action listener
/* Add Action Listeners */
cmdAddItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
AddPurchase addPurchase = new AddPurchase(
(radWeight.isSelected()) ? 'w' :(radQty.isSelected()) ? 'q' : 'u',
txtNameOfItem.getText(),
txtAmount.getText(),
txtUnits.getText(),
txtPricePerUnit.getText());
ShoppingApplication sa = new ShoppingApplication();
Object[][] newData = sa.generatePurchaseTableData();
//TODO make tblBill updata it's contents
}
});
From the code above, it does look like I haven't made much effort, but I've actually been trying to get this to work for hours now, tried using different methods, data structures and been getting no where to went right back to the start, and that is what the above code it.
I've Googled this a bit, and can't seem to find anything, can't think why no one else has seemed to get stuck on this. (maybe I'm just being thick) but hopefully this post will help others too.
Thanks in advance :)
The JTable has a data model (TableModel), which either holds the values, or is an adapter to the actual data.
Data in a table can be update by either changing the data in the table model, or by setting a new table model.
In your case, you could use the javax.swing.table.DefaultTableModel:
TableModel tableModel=new DefaultTableModel(newData, tableHeadings);
tblBill.setModel(tableModel);
update when the user presses the "Add Item" button.
Why do recreate the entire table when you only add a single item? That is not very efficient.
Instead must add a new row to the table. This code (like the above code) assumes you are using the DefaultTableModel:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(...);
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.
in my project i want select fill the jcombobox which are have for COUNTRY,STATE,CITY
when i click on counrty then it should be appear related in that country how many sate are have and then same thing with state also for city
here is my code tell me where is wrong and what it'll be right code for this
private void cmbcountryPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
try{
//JOptionPane.showMessageDialog(null,"hello");
String sql= "SELECT StateName From state where Country_Id=? ";
prst=con.prepareStatement(sql);
prst.setString(1, cmbcountry.getSelectedItem().toString());
prst.execute();
rs=prst.executeQuery();
if(rs.next()){
cmbstate.setSelectedItem(rs.getString("state"));
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
fillstate(cmbcountry.getSelectedIndex());
}
Your question is not very clear but i think you have three comboboxes. Country, State and City and you want to populate States on the basis of Country selected and Cities on the basis of State selected.
If that is what you want then the easiest option would be:
//notice the use of while instead of if as there would be multiple values
cmbstate.removeAllItems();
Vector<String> items = new Vector<String>();
while(rs.next())
{
items.addElement(rs.getString("state"));
}
ComboBoxModel model = new DefaultComboBoxModel(items);
cmbState.setModel(model);
Similarly for the city combobox when state is selected.
Creating a new Model everytime is not the best way so another option could be call cmbState.addItem(String); from wihin the loop.
In any case you may need to remove the listeners from the combobox you are playing with as the listeners are fired when you make any changes in the data. You can do something like:
ItemListener[] itemListeners = cmbState.getItemListeners();
for(ItemListener l: itemListeners )
cmbState.removeItemListener(l);
//do what you want with the combo here.
for(ItemListener l: itemListeners )
cmbState.addItemListener(l);
Having read here and not understood the concept, I had to post my issue here. I am trying take the input value from Keyword JTextField and filter my JTable table_job.
When search button is pressed, it should change the table in Job List panel to only display the set of jobs which includes the keyword in any of the column in its table. Currently, I am having no luck and am getting blank screens.
Here is the Job List Screen
The table on right does not update according to keyword.
Here is what I tried and failed, I am new to table filtering.
try {
jobTableInit();
String value = keyword.getText();
TableRowSorter sorter;
sorter = new TableRowSorter<DefaultTableModel>(new DefaultTableModel());
RowFilter<DefaultTableModel, Object> rowFilter = null;
try {
rowFilter = RowFilter.regexFilter(keyword.getText());
}
catch(java.util.regex.PatternSyntaxException ex) {
return;
}
sorter.setRowFilter(rowFilter);
table_job.setRowSorter(sorter);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Can somebody suggest recommendations or show me a simple example code?
by default there are two ways
use custom Comparator and search in the XxxTableModel (or JTables view by using Pattern), more about Comparator is described in JTables tutorial about Sorting and Filtering
use built_in RowFilter in TableRowSorter, then filtered JTables view returns desired List_of_Xxx
another idea is only to hightlighting matches
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);
}