Updating JTable when selecting item in combobox in Java - java

I coded auto suggesting comboBox that retrieve data from SQL database.It was successful.
Then as next step, I want these functionalities to be done,
*When user select a "ItemID" from the comboBox(When the user type first letter of ItemID, suggest list comes and user can select aItemID - successfully coded), JTable's "ItemID" column and other columns that related to that specific "ItemID" must be updated from the database.
I coded updateTable()method as below;
private void updateTable(){
String existID = (String) IDcombo.getSelectedItem();
String sql = "select * from druginfo WHERE ItemId LIKE '"+existID+"%'";
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
saleTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
} }

Well your tablemodel needs to fire according to the event. If only table data changes then it should fire fireTableDataChanged(). If data and structure both changes then it should fire fireTableStructureChanged(). You can refer to the document
If you're still having trouble with this the one way is to call repaint on your table but that's not a very good way of doing things.

Related

Displaying data in JTextfield from two different mysql tables

Cheers everyone, beginner here!.
I'm currently working on a Java application to keep track of the inventory in our warehouse. It's all on localhost until it's finished. I've created two tables in MySQL database: one table shows the article code, location and quantity (VOORRAADSYSTEEM); the other table shows article code and description (STAMDATA).
In my GUI, I've got a JTable which loads data from VOORRAADSYSTEEM, and on mouseclickevent (getSelectedRow) shows the data in the corresponding JTextFields (so far so good). The only field not showing is the description field (which should be read from the STAMDATA table).
I've tried creating a method for this specific part of the program. The method runs a query to the second table using a inner join to the first table. Here's the code below.
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(2, sql);
descriptionTxt.setText(rs.getString(sql));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
At this moment I'm not exactly sure how to approach this problem. I'm also going to try using foreign keys. Any help would be appreciated.
There are better ways to handle what you want to do. For instance you could get all the information you need with one query by joining the table on a common column (ARTICLENUMBER and ARTICLECODE) and then display it.
Right now it looks/sounds like you might be trying to get all the information with two queries.
However, there are some errors with your load description method:
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
ResultSet results = conn.createStatment().executeQuery(sql);
if(results.next()) //make sure something was returned to avoid null pointer exception
descriptionTxt.setText(rs.getString("DESCRIPTION"));
else
JOptionPane.showMessageDialog(null, "no results returned");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This should work a little better for you.

Same code for two jtables but one of them isn't getting values from SQL table

Kindly help me to solve this problem, also tell me how to display data on the table by using condition on comboBox. Following is the code and Output. Please help me, as I have to show this to my instructor tomorrow.
public ArrayList<User> userList() {
ArrayList<User> usersList = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(url);
String query = "SELECT * FROM tbl_Income";
Statement st=con.createStatement();
ResultSet rs= st.executeQuery(query);
User user;
while(rs.next()){
user= new User(rs.getInt("Amout"),rs.getString("Date"),rs.getString("Source"));
usersList.add(user);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return usersList;
}
public void show_user() {
ArrayList<User> list = userList();
DefaultTableModel model = (DefaultTableModel)Income_Table.getModel();
Object[] row =new Object[3];
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getAmout();
row[1]=list.get(i).getDate();
row[2]=list.get(i).getSource();
model.addRow(row);
}
}
//**********tbl_Expense
public ArrayList<User_E> userList_E() {
ArrayList<User_E> UsersList_E = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String eurl="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(eurl);
String query_E = "SELECT * FROM tbl_Expense";
Statement stt=con.createStatement();
ResultSet rst= stt.executeQuery(query_E);
User_E user_e;
while(rst.next()){
user_e = new User_E(rst.getString("ExpenseDetail"),rst.getString("Category"),rst.getString("Date"),rst.getInt("Amount"));
UsersList_E.add(user_e);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return UsersList_E;
}
public void showuser_E(){
ArrayList<User_E> list_E = userList_E();
DefaultTableModel model_e = (DefaultTableModel)Expense_Table.getModel();
Object[] row_e =new Object[4];
for(int i=0;i<list_E.size();i++){
row_e[0]=list_E.get(i).getAmount();
row_e[1]=list_E.get(i).getDate();
row_e[2]=list_E.get(i).getCategory();
row_e[3]=list_E.get(i).getExpenseDetail();
model_e.addRow(row_e);
}
}
This is the Output, getting 0 instead of original data
I cannot tell what the issue by looking at the code posted. But, the application's database access, querying and showing the data in the GUI need to be structured something like this:
1. Access database and get connection:
Get connection object for the database DB_Project (there is no need to create connection objects twice).
2. Query 1:
Create statement
Query the tbl_Income table and populate the "userList"
Close the statement (this also closes the corresponding result set)
3. Query 2:
Create statement
Query the tbl_Expense table and populate the "userList_E"
Close the statement
4. Close connection (this is optional and depends on application requirement).
5. Display GUI using the queried data:
Show user income JTable using the "userList"
Show user expense JTable using the "userList_E"
NOTES:
Place some debug or log statements in the Java code and verify if there is any data in the tables being queried and also what kind of data it is. Querying the database tables directly and interactively or from the command prompt also helps. Also, after populating the list collections print the lists onto the console using System.out.prinltln() statements to verify if the data is populated to them properly.
How to display based on combo box selection:
Here is the link to Java tutorials on using Swing JComboBox - see the section "Handling Events on a Combo Box".
There are different ways one can build the code to acheive this functionality.
By directly querying the database table using the data selected from
the combo box, or
By filtering the data from the "list" data already queried and populated to it. This option requires the queried data from the database tables be stored in instance variables.
Again, it depends upon the application requirement. In case the database table data is not changing then option 2 is the correct method, otherwise query the database table directly.
One hideous thing: nothing is closed (connection, statement, result set).
Try-with-resources may help here, to automatically close those, even on return, break, raised exception.
public ArrayList<User_E> userList_E() {
ArrayList<User_E> usersList_E = new ArrayList<>();
String eurl = "jdbc:sqlserver://localhost:1433;databasename=DB_Project;"
+ "user=User;Password=password";
String query_E = "SELECT * FROM tbl_Expense";
try (Connection con = DriverManager.getConnection(eurl);
Statement stt = con.createStatement();
ResultSet rst= stt.executeQuery(query_E)) {
while(rst.next()){
User user_e = new User_E(rst.getString("ExpenseDetail"),
rst.getString("Category"),
rst.getString("Date"),
rst.getInt("Amount"));
usersList_E.add(user_e);
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
return usersList_E;
}
Class.forName on the driver class is since years no longer required.
For the error: I can only assume that the application is running out of free connections.

JTable shows duplicate values while trying to populate it

I am implementing the search book frame in my library management system project. In this frame, I want to check the availability of the book. I have two database tables:
1 Book:-which keeps the records of all the books in the library
2 Issuebook;-which keeps the record of issued book
When I am running the frame, the JTable gets populated with the same value thrice. The output is attached after the code. I am unable to find the problem. Here's my code:
public void actionPerformed(ActionEvent e) {
String bookname=tfBookName.getText();
int count=0;
try{
con=DemoConnection.getConnection();
ps=con.prepareStatement("select book.bookid from book,issuebook where book.bookid!=issuebook.bookid and bookname=?");
ps.setString(1, bookname);
rs=ps.executeQuery();
while(rs.next())
{
count++;
String bookid =rs.getString(1);
String availability="Available";
Object[] row = { bookid, bookname, availability};
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.insertRow(0,row);
}
ps1=con.prepareStatement("select book.bookid from book,issuebook where book.bookid=issuebook.bookid and bookname=?");
ps1.setString(1, bookname);
rs1=ps1.executeQuery();
while(rs1.next())
{
String bookid =rs1.getString(1);
String availability="Issued";
Object[] row = { bookid, bookname, availability};
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.insertRow(0,row);
}
if(rs==null&&rs1==null)
{
JOptionPane.showMessageDialog(frame, "Book named"+bookname+"does not exist!!");
}
else if(rs==null&&rs!=null)
{
JOptionPane.showMessageDialog(frame, "All the copies of"+bookname+" book are issued!!");
}
else if(rs!=null&&rs==null)
{
JOptionPane.showMessageDialog(frame, "All the copies of"+bookname+" book are avaialble!!");
}
else if(rs!=null&&rs!=null)
{
JOptionPane.showMessageDialog(frame, count+" copies of"+bookname+" book is avaliable!!");
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
});
Here's output. When the book which is issued, it is shown in the table; no duplicate entries were filled up, but duplicate entries get filled in table for the available books.
As #Blip stood out, the problem lies in your SQL query, especially the first one
select book.bookid from book,issuebook where book.bookid!=issuebook.bookid and bookname=?
In this query, you get the book.bookid each time it is different from an issuebook.bookid. So as you have 3 records in your issuebook table, you get 3 results when a book is not present in this table. Directly trying this query on your console should point this out.
The solution can be to modify your query as
select book.bookid, IF(issuebook.bookid IS NULL, 'Available', 'Issued') as availability from book,issuebook where LEFT JOIN availability ON (book.bookid, issuebook.bookid) and bookname=?
I'm not very used to MySQL and the "LEFT JOIN" notation, but the idea is to automatically get the availability status depending on weither or not the bookid is present in the issuebook table or not. So maybe there is some syntax flaws in my sample query...
Anyway like this you just have to do ONE SQL query (get rid of this ps1, res1...) and get the availability with
String availability=rs.getString(2);
If you are not familiar with SQL JOIN, I advise to document yourself on the subject :).
Hope this will help ;)

Load data to a combo box

I have two combo boxes.1 is for main department and other is for sub department. I want to load all the data in Main_department table to combo box. When selecting combo box item i want to load sub_departments relevant to that selected item.
try {
Conn c=new Conn();
Statement s=c.createConn().createStatement();
String query ="SELECT * FROM main_dep";
ResultSet rst = s.executeQuery(query);
DefaultComboBoxModel dc=(DefaultComboBoxModel)maindep.getModel();
while(rst.next()){
dc.addElement(rst.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
This is how i got the main Departments. Then i wrote following code for itemStateChange event in main Department combobox.
String main = maindep.getSelectedItem().toString();
Conn c=new Conn();
try {
//Conn c=new Conn();
Statement s=c.createConn().createStatement();
String query ="SELECT Description FROM sub_dep WHERE Main_dep_ID IN (SELECT Main_Dep_Id FROM main_dep WHERE description = '"+main+"')";
ResultSet rst = s.executeQuery(query);
DefaultComboBoxModel dc=(DefaultComboBoxModel)subdep.getModel();
while(rst.next()){
dc.addElement(rst.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
When Main Department is changed sub Departments relevant to that department is loaded to sub Department combobox. But loaded items are Still remaining when another one is selected.
How can i overcome that issue?
But loaded items are Still remaining when another one is selected
You can use:
dc.removeAllElements();
before you start adding new elements to the model.
This case call dependent combo-box.
You have to load data to first combo-box first then, when user select the value of that combo-box, it will cal Ajax or another technology back to server to retrieve data to second combo-box.So , that is idea.
You can see this link for reference here

How to get selected rows from a database into a jTable?

I have a database table which has many patient details like registration id, registration date etc. I want to perform a date based search of the patients and get the result into a jTable. ( for example, if I type 23-05-2013 as the registration date, all the patients admitted on 23 May should be displayed in a jTable. How do I do that?
This is the code I have used:
public void getTableData() {
try {
con = getConnection.getCon();
String sql = "SELECT * FROM patientrecords WHERE Registration Date = ?";
pst.setString(1, regdate.getText());
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
patient_table.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
1) You should make your own TableModel implementation or extending AbstractTableModel
2) Map patientrecords to object world. Also entity name should be in singular. So you will have a java-bean like PatientRecord.
3) You'll have a List<PatientRecord> data as DataHolder.
Fill like
while (rs.next()) {
data.add(new PatientRecord(..));
}
4) In some part you should set in your jtable.setModel(..)
This previous question may help you simple code to populate jtable from resultset

Categories