Populate combo box with table values - java

EDIT(NEW):
Still haven't figured out how to populate the cboxCustomers. I've been at it for the past day or two, but without luck.
In case anyone can help: http://pastebin.com/e5wibRYw
I went from cats to customers, btw.
I tried Mr. Xymon's approach, but didn't implement it correctly since it didn't work.
Whatever event I used to handle the population I always got NullPointerException for whatever control/event I was trying to use.
OLD:
There's a JForm. On it, there's a single combo box. Also have a single table with cats - cats. Each cat has id, and catName.
What I wanted to do was when I click on the combo box, thus expanding it, populate it with all id of cats that are found in cats table.
SLOVED. Asnwer below.
Unfortunately I receive numerous unreported exception java.sql.SQLException from the lines I've indicated with >:
private void cboxCatsMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
// create an array list to be filled with cat's ids
ArrayList<String> cats = new ArrayList<String>();
String query = "SELECT id FROM cats ORDER BY id";
>java.sql.PreparedStatement stm = connection.prepareStatement(query);
>ResultSet rs = stm.executeQuery(query);
>while(rs.next()){
>String cat = rs.getString("id");
// add cat's ids tp the array list
cats.add(cat);
}
>rs.close();
// populate the combo box
DefaultComboBoxModel model = new DefaultComboBoxModel(cats.toArray());
cboxCats.setModel(model);
}
OLD ANSWER:
I think I fixed it. I just had to wrap all of the highlighted lines of code together into one big try-catch statement that would catch SQLException. Problem is - the combo box doesn't get populated with id values when I expand it. Why is that? Am I using the wrong event?

Isn't better to populate your combo box with cat's name instead of the id? I came up with a different solution by directly adding field value into model instead of using ArrayList. You have to perform it within the constructor to populate the combo box upon loading the form.
DefaultComboBoxModel list = new DefaultComboBoxModel();
JComboBox cbo_cats = new JComboBox(list);
// at constructor or a user-defined method that's called from constructor
try{
// assume that all objects were all properly defined
s = con.createStatement();
s.executeQuery("SELECT * FROM cats ORDER BY catName");
rs = s.getResultSet();
while(rs.next()){
//int id = rs.getInt("id");
//list.addElement(id);
String c = rs.getString("catName");
list.addElement(c);
}
}catch(Exception err){
System.out.println(err);
}
As you can see I didn't use prepared statements but you can easily change that.

Related

Return type of method which fill comboBox

I'm working on a simple GUI where I drag combobox and edit the values here I i have a class categories and then 3 methods of rice,sweets and meal. I would like to be to call these three methods on my frame and then from there I want to fill the values into the combo box. An important thing that these 3 methods of categories class are connected with access so they fetch data from there. My question is: What will be the return type of these particular methods?
public String rice()
{
String query ="select * from categories";
String end=null;
String a ;
try{
ps=conn.prepareStatement(query);
rs=ps.executeQuery();
while(rs.next())
{
end=end+rs.getString("Rice")+"\t";
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return end;
}`
now in another class
Combo_boxes obj = new Combo_boxes();
comboBox.addItem(obj.rice());
When I call this method it will to return a value of 1 row of database and then I want to place it into the combo box and then next row so from this,i will place every item from database. When I update my database it should automatically update the combo box.

Multiple entries in a JTable from a Database

This is my first question here and I hope I am not repeating someone else's question. I will try and explain the problem as much as I can in the next few lines. Pardon my English if its really bad .
So I have here a JTable in which I would like to retrieve values from a database. So far I can add 1 value and I know why this is. The question is . How do I add multiple values to this table ?
This is the method I use in my operations to find a gun in a specific shop with its quantity
public ResultSet gunSearch(String id, int qty, int storeId) {
try {
String s = "SELECT gunID, gunName AS \"Gun Name\", gunPrice AS \"Price\", SellCost AS \"Cost\", availableQty AS \"Amount Available\", "+qty+" AS \"Quantity\" FROM Guns WHERE gunId = '" + id + "'AND storeId='"+storeId+"'";
pstmt = conn.prepareStatement(s);
rset = pstmt.executeQuery(s);
} catch (Exception ex) {
System.out.println("Error here at searchByProdId Operation "+ex);
}
return rset;
}
For my GUI I use the following code to display the information entered by the user
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(enterBtn)){
String gunID = gunIdText.getText();
int qty = Integer.parseInt(quantityText.getText());
table.setModel(DbUtils.resultSetToTableModel(op.gunSearch(gunID, qty, storeId)));
Whenever I click the Enter button the column of data is retrieved from the database. However if I re-enter another gunId and quantity , the previous column disappears and the new column of data is retrieved from the database.
How could I possibly , enter couple of different gunId's and quantitie's into the JTable ?
Your gunSearch method only returns one result. You then completely recreate the TableModel from this one result, erasing whatever you had in the old model.
You'll need to concoct a new method that can take a Collection<String> (a collection of gun ids) and return a row for each id provided.
Alternatively, you can create a method that adds a gun to an existing TableModel rather than recreating the whole model from scratch every time. It depends on how you want the application to work, which option is better.

null pointer exception can't be fixed

I'm implementing a software for a stock management system in java.I'm using MVC design pattern and i found this exception when trying to fill a JcomboBox. I want to get all the batches when a item-code is being passed into the method.so the method should return a array-list of relevant objects. but when I run this program it gave me this kinda error and it says there is empty result set. but i also tried the sql code manually in the terminal and it worked. so i can't imagine how to fix this error. i'm glad if anyone can tell me where is the problem. I tried to post my screen shots but it cannot be done as i don't have enough reputation
here is my code
String sql = "select batchNo from MainBatch where itemCode = ?";
Connection c=DBConnection.getInstance().getConnection();
PreparedStatement ps=c.prepareStatement(sql);
ps.setString(1, itemCode);
System.out.println(itemCode+" -----> item code is thiss");
ResultSet set=ps.executeQuery();
ArrayList<MainBatch> list=new ArrayList<>();
System.out.println(set.next()+" <-----result set is");
while (set.next()) {
MainBatch batch=new MainBatch(set.getString("batchNo"));
list.add(batch);
}
return list;
[
ResultSet.next() moves the result set's cursor to the next row. When you print it, before the while loop, you're losing the first row (or the only row in a single row result set). Personally, I'd just omit it, but if you have to have it, you could extract the result to a local variable:
boolean next = set.next();
System.out.println(next + " <-----result set is");
while (next) {
MainBatch batch=new MainBatch(set.getString("batchNo"));
list.add(batch);
next = set.next();
}
return list;
Remove this line.
System.out.println(set.next()+" <-----result set is");
You are calling set.next() twise, this moves the resultset pointer to next row.

Dynamic GUI Creation from ResultSet - Java

I'm trying to create a Java GUI dynamically by taking values from a result set and using it to generate a checklist. I've created a small demo program to demonstrate what I've done:
SQL Commands
CREATE USER 'test'#'localhost' IDENTIFIED BY 'testpw';
CREATE DATABASE combotest;
USE combotest;
CREATE TABLE combotable (
id INT(5) NOT NULL PRIMARY KEY auto_increment,
type VARCHAR(50) NOT NULL);
INSERT INTO combotable (id, type) VALUES
(default, 'Label'),
(default, 'Textfield'),
(default, 'Combo'),
(default, 'Label'),
(default, 'Textfield'),
(default, 'Combo'),
(default, 'Combo');
GRANT SELECT ON combotest.* TO 'test'#'localhost';
For your convenience if you'd like to test it yourself I've put all the SQL commands above.
Now, for my Java code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
public class resToComboDemo implements ActionListener {
//JDBC Variables
static Connection connect = null;
static Statement statement = null;
static ResultSet res = null;
#SuppressWarnings("rawtypes")
//Other Variables
JComboBox comboBox;
JButton submit;
JFrame frame;
JLabel label;
JTextField textField;
Container pane;
public static void main(String[] args) throws SQLException {
new resToComboDemo();
}
public resToComboDemo() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost/combotest?"
+ "user=test&password=testpw");
statement = connect.createStatement();
//Note: in this specific case I do realize that "order by id" is not necessary. I want it there, though.
res = statement.executeQuery("SELECT * FROM combotable ORDER BY id");
createStuff(res);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error 1: "+e, "Error!", JOptionPane.ERROR_MESSAGE);
} finally {
connect.close();
}
}
#SuppressWarnings({"rawtypes", "unchecked" })
public void createStuff (ResultSet res) throws SQLException {
frame = new JFrame("Testing dynamic gui");
Dimension sD = Toolkit.getDefaultToolkit().getScreenSize();
int width = sD.width;
int height = sD.height - 45;
frame.setSize(width,height);
pane = frame.getContentPane();
pane.setLayout(new GridLayout(0, 2));
while (res.next()) {
Object[] options = { "Pass", "Fail"};
String type = res.getString("type");
JLabel label = new JLabel("<html><small>"+type+"</small></html>");
JLabel blank = new JLabel(" ");
blank.setBackground(Color.black);
blank.setOpaque(true);
if (type.equals("Label")) {
label.setBackground(Color.black);
label.setForeground(Color.white);
label.setOpaque(true);
pane.add(label);
pane.add(blank);
} else if (type.equals("Combo")) {
pane.add(label);
comboBox = new JComboBox(options);
pane.add(comboBox);
} else if (type.equals("Textfield")) {
pane.add(label);
textField = new JTextField(20);
pane.add(textField);
}
}
JLabel blank2 = new JLabel(" ");
pane.add(blank2);
submit = new JButton("Submit");
submit.addActionListener(this);
pane.add(submit);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Now, everything works great with creating the GUI here. However, I need to be able to treat the Combobox and Textfield components as their own separate entities. Meaning, I want to be able to get user input from each different component. Right now, if I were to request information from textfield, it just gives me the information from the last textfield. This makes perfect since, because that's how java reads it. I have no problem with that.
I just can't for the life of me figure out how to get each component's input separately. Perhaps by taking the result set and adding the results to some type of array? I've attempted this multiple times in different flavors and I can't get it to come out the way I need it to. Some of you are going to request that I show you what I've tried... but honestly, it's not worth it.
And, before anybody asks: No, I will not use FlowLayout. :)
Any help is greatly appreciated!
There are probably a few ways to achieve this based on what you want to do...
If you are only performing a batch update, you could use a Map keyed to the id of the row and mapping to the Component.
This way, when you want to save the values back to the database, you would simply iterate the Maps key values, extract the Component associated with each key and then extract the value of the Component...
I might consider making a wrapper interface which has a simple getText method and wrap the component within it, making the implementation of the wrapper responsible for extracting the text, but that's just me ;)
If you want to perform updates when a individual component is updated, you would need to swap the mapping, so that the Component would the key and the id would be mapped to it.
This would mean that when some kind of event occurred that would trigger and update (ie a ActionEvent), you could extract the source from the event and look up the id in the Map based on the Component that caused the event...
Now...frankly, I would simply use a JTable and create a custom TableModel which could model all this.
This would require you to create POJO of the table, maintaining the id, type and value within a single object. This would define a basic row in the table.
The only problem is you would need to create a (reasonably) complex TableCellEditor that could take the type and return an appropriate editor for the table. Not impossible, it's just an additional complexity beyond the normal usage of a table.
This would all the information you need is available in a single object of a single row in the table.
Take a look at How to use tables for more details
Equally, you could use a similarly idea with the Map ideas above...
You could also simply create a self contained "editor" (extending from something like JPanel), which maintain information about the id and type and from which you could extract the value and simply keep a list of these....for example...
what about interrogating the Container ( pane) which contains the components
getComponents() method and loop through the sub component and check for JComobox and JTextField do the required cast and retrieve the value
Just an idea in case you are against adding the sub-components into a kind of list
You only have a reference to the last text field or combo box that you create, since you are reusing the variables that hold them. I would put them in an ArrayList, store each new text field and combbox as you create them, then you can go back and get input from all of them after you're done.
---------- (after the OP's response to the above paragraph)
No, there is no "place to refer you" -- it's your set of requirements, it would be pretty remarkable to find code that already existed that did this exact thing. Java and Swing give you the tools, you need to put things together yourself.
You don't show your "actionPerformed" routine, but let's hypothesize about it for a minute. It is called by the framework when an action is done, and it is passed an "ActionEvent" object. Looking through its methods, we find that it has "getSource()", so it will give you a reference to the component which generated the event.
Let's further think about what we have -- a set of components in the UI, and ones which can generate events are interesting to us. We want to, in this case, retrieve something from the component that generated the event.
If we have the component (from actionEvent.getSource()) and we want to do something with it, then we can, at worst do something like the following in the actionPerformed() method:
Component sourceComponent = actionEvent.getSource();
if (sourceComponent instanceof JComboBox)
{ JComboBox sourceBox = (JComboBox) sourceComponent;
// get the value from the combo box here
}
else if (sourceComponent instanceof JTextField)
{ JTextField sourceTextField = (JTextField) sourceComponent;
// get the value from the text field here
}
// or else do nothing -- our action was not one of these.
Done this way, you don't even need to keep a list of the components -- the UI is keeping a reference to all of them, and you just use that reference when the actionEvent occurs.
Now, this is not the only or even the best or the simplest way of doing this. If you wanted to extend JComboBox and JTextField with your own classes, you could have those classes both implement an interface that defined something like getValue() or getText; then you would not need the ugly instance of operator, which can usually be done away with by better design and planning.

Need to delete from multiple JLists instead of just the one

I have 3 jlists. I have a button that is used to delete a selected item from the Patient Jlist but I also need it to delete from my history Jlist and Invoices Jlist. I have it deleting from one but I dont know how to implement the code to delete from the history jlist and invoices jlist.
Here is my code to delete from 1 JList which works!:
JButton btnDeleteDB = new JButton("Delete From DB");
btnDeleteDB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int selectedIndex = patientList1.getSelectedIndex();
if (selectedIndex != -1) {
int x = patientList.get(selectedIndex).getID();
String query =
"DELETE FROM `patienttable` WHERE `patientid` ='"+x+"' LIMIT 1";
try {
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/denistassignment","root","");
Statement s = (Statement) con.createStatement();
s.execute(query);
} catch (Exception ex) {
ex.printStackTrace();
}
patientListModel.remove(selectedIndex);
patientList1.remove(selectedIndex);
}
}});
btnDeleteDB.setBounds(320, 500, 125, 23);
contentPane.add(btnDeleteDB);
Your code shows quite a few design flaws I'm afraid, I will list some before answering your question:
Remove the code which removes the item from the DB and the list from the ActionListener and place it in a private method so you have easy access to it from other listeners if needed, to enhance readability and to avoid code duplication.
You are not closing neither the DB connection nor the statement. Do so.
Don't catch general Exceptions, and don't just call e.printStackTrace() unless for explicit debug code which is removed before production.
patientList1.remove(selectedIndex); has nothing to do with removing an item from the JList, consult the JavaDoc of this method for details. In short, remove that line.
I suppose all your JLists are in the same class and you have member variables pointing to each. If so, then just locate the corresponding objects which should also be removed in your other JLists at the same time you are locating the index of the currently selected one. I don't know the details of your system, so maybe iterate over the other list items, compare IDs with the ID of the one you want to delete and then just call listXY.getModel().remove(indexOfItem) for each one you want to delete.

Categories