jTable not adding the whole data from Object defined - Java - Netbeans - java

I have a button in which after pressing it, the items that are in critical level will populate the jTable. I have managed to do it but the issue i'm facing is that the row it adds just populates the first column and leave the rest blank. My questions are, how come it only populates the first column and how do I get the rest of the columns filled?
PS. The table columns are PRODUCT NAME - STOCK ON HAND - MINIMUM QTY
yet, the first column shows the stockOnHand not even the productName.
Below are my codes for the button:
DefaultTableModel model = (DefaultTableModel)tableMinimum.getModel();
try{
String viewCriticalSQL = "Select * from tblProduct";
pstmt = conn.prepareStatement(viewCriticalSQL);
rs = pstmt.executeQuery();
while(model.getRowCount()>0){
model.removeRow(0);
}
while(rs.next()){
String prodName = rs.getString("productName");
int getStock = rs.getInt("stockOnHand");
int getMinimum = rs.getInt("minimumOrder");
if (getStock<getMinimum){
Object[] adRow = {prodName, getStock, getMinimum};
model.addRow(adRow);
}
}
}catch(SQLException e){
JOptionPane.showMessageDialog(this, e.getMessage());
}

Related

Getting Multiple Data using Text field + Jbutton from SQL Server to Jtable

Good day, just wanna ask. I have a Java GUI where I want to add multiple data from SQL server to my Jtable. The flow here is that I would want to use the text field as search field where I will add the info for searching and use the Jbutton to perform the search action then it will give/show me the data to my Jtable. Actually the code is running however some of the data like the 1st data added to my SQL serve and from data id 7 and and up are not showing. How would I fix this and show multiple data with same order ID form SQL server?
Thank you!!
try {
String query = "select * from `sales_product` where order_id = ?";
pst = con.prepareStatement(query);
pst.setString(1, txsearch.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
while(rs.next()) {
String prodname = rs.getString("prodname");
String price = String.valueOf(rs.getInt("price"));
String qty = String.valueOf(rs.getInt("qty"));
String total = String.valueOf(rs.getInt("total"));
model = (DefaultTableModel) datatable.getModel();
model.addRow(new Object[]{
prodname,
price,
qty,
total
});
int sum = 0;
for (int a = 0; a < datatable.getRowCount(); a++) {
sum = sum + Integer.parseInt(datatable.getValueAt(a, 3).toString());
}
Ltotal.setText(Integer.toString(sum));
}
}
else {
JOptionPane.showMessageDialog(this, "No order found!");
txsearch.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(milktea.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(rs.next()) {
while(rs.next()) {
No need for the if (rs.next()) statement. That is causing you to skip the first row of data in the ResultSet.
All you need is the while (rs.next()) statement to create the loop to read all rows in the ResultSet.

JTable - Filter data

I'm trying to filter a JTable but the results are not as expected.
Below is the JTable with the added elements (I'm using MySQL to store the Data)
JTable with contents - Picture
When I try to filter the list for someone specific, I do not get the data from the table. For example, I search for "Ana" and nothing appears.
Search results for "Ana" - Picture
If I try to search using some "numbers", like the salary, I get the right result but the ID is not right. Pictures to clarify the issue below.
Wrong ID
Right ID
The Code to generate the ArrayList with the employees :
public static ArrayList<Angajat> listaAngajati() {
ArrayList<Angajat> listaAngajati = new ArrayList<>();
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/angajati", "root", "***");) {
Statement st = conn.createStatement();
st.executeQuery("select * from angajati");
ResultSet rs = st.getResultSet();
Angajat angajat;
while (rs.next()) {
angajat = new Angajat(rs.getInt("id"), rs.getString("nume"), rs.getString("prenume"), rs.getInt("varsta"), rs.getString("adresa"), rs.getDouble("salariu"));
listaAngajati.add(angajat);
}
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
return listaAngajati;
}
public static void arataAngajati() {
ArrayList<Angajat> arataAngajati = listaAngajati();
DefaultTableModel model = (DefaultTableModel) tabelangajati.getModel();
Object[] rand = new Object[6];
for (int i = 0; i < arataAngajati.size(); i++) {
rand[0] = arataAngajati.get(i).getID();
rand[1] = arataAngajati.get(i).getNume();
rand[2] = arataAngajati.get(i).getPrenume();
rand[3] = arataAngajati.get(i).getVarsta();
rand[4] = arataAngajati.get(i).getAdresa();
rand[5] = arataAngajati.get(i).getSalariu();
model.addRow(rand);
}
}
Code to filter the JTable
private void cautaInTabelKeyReleased(java.awt.event.KeyEvent evt) {
DefaultTableModel tabel = (DefaultTableModel) tabelangajati.getModel();
String query = cautaInTabel.getText().toLowerCase();
TableRowSorter<DefaultTableModel> sort = new TableRowSorter<DefaultTableModel>(tabel);
tabelangajati.setRowSorter(sort);
sort.setRowFilter(RowFilter.regexFilter(query));
}
Question : How can I modify the code so when I try to search for a an employee using his name to get the right result (not like now - no results) and when trying to modify the employee data, to get the right ID as shown in the JTable (example in the pictures above) ?
EDIT
In order to filter the data from the table accordingly I had to use
sort.setRowFilter(RowFilter.regexFilter("(?i)" + query));
When I was filtering the table, only the view modified and not the values from the row (Even if I saw the values from the row 3 and values on the backend where from the row 1). I managed to modify the following row and the table works perfectly.
From :
int row = tabelangajati.getSelectedRow();
To :
int row = tabelangajati.convertRowIndexToModel(tabelangajati.getSelectedRow());

Array Index Out Of Bounds Exception When trying to update MySQL database in Java

I have a sale table in jframe form, user adding a row one at a time.
I want to reduce instock in MySQL table saleifo by reducing qty column in the table.
Code segment for save and print button ;
DefaultTableModel model = (DefaultTableModel) tableSale.getModel();
if(model.getRowCount()==0){
JOptionPane.showMessageDialog(null, "You have nothing to Print or Save ");
}else{
int save = JOptionPane.showConfirmDialog(null, "Do you really want to Save the Invoice Data ?","Save Confirmation",JOptionPane.YES_NO_OPTION);
if((save)==0){
try{
String saledate = ((JTextField)dayChooser.getDateEditor().getUiComponent()).getText();
String invoice = InvoiceNo_txt.getText();
String citems = countitems_txt.getText();
String tDis =totalDiscount_txt.getText();
String ntotal = NetTotal_txt.getText();
//setting data to saleinfo db table
try{
String sql = "Insert into saleinfo (SaleDate,InvoiceNo,TotalItems,TotalDiscount,NetTotal)values (?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, saledate);
pst.setString(2, invoice);
pst.setString(3, citems);
pst.setString(4, tDis);
pst.setString(5, ntotal);
pst.execute();
}catch(Exception e){
}
//redusing stock in db
int rcount = tableSale.getRowCount();
String idsale = (String) tableSale.getModel().getValueAt(rcount, 0);
String sql0= "select * from druginfo where ItemID=?";
pst0=conn.prepareStatement(sql0);
pst0.setString(1, idsale);
rs0= pst0.executeQuery();
if(rs0.next()){
String instock = rs0.getString("InStock");
int nowstock=Integer.parseInt(instock);
int soldqty = (int) tableSale.getModel().getValueAt(rcount, 3);
int newstock = nowstock - soldqty;
System.out.println("new :"+newstock);
String sqlupdate= "update druginfo set InStock='"+newstock+"' where ItemID='"+idsale+"'";
pst=conn.prepareStatement(sqlupdate);
pst.execute();
System.out.println("Done");
}
But shows an ArrayIndexOutOfBoundsException.
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
at java.util.Vector.elementAt(Vector.java:474) at java.util.Vector.elementAt(Vector.java:474)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at com.bit.project.Newsale.saveprint_btnActionPerformed(Newsale.java:1039)
at com.bit.project.Newsale.access$1300(Newsale.java:57)
at com.bit.project.Newsale$16.actionPerformed(Newsale.java:683)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
Line 1039 is String idsale = (String) tableSale.getModel().getValueAt(rcount, 0);.
How to fix this?
At line 1037 you assign the number of visible rows in the table to the int rcount, which in this case is 2. However on line 1039 you use this value to attempt to get the value of "row 2, column 0" from the table model.
As row and column indices start from 0, and there are only two rows numbered 0 and 1, it's no wonder there is a problem when you ask for row 2!
If your intention is to get the value of the cell in the first column and last row of the table, then you need to change line 1039 to:
String idsale = (String) tableSale.getModel().getValueAt(rcount-1, 0);
You are already checking that rcount > 0 by the time execution reaches this point so this shouldn't cause trouble. Except...
It's worth noting that if the table has a RowSorter attached to it, then the number of visible rows (sa returned by tableSale.getRowCount() may well be less than the number of actual rows in the underlying table model (as returned by tableSale.getModel().getRowCount(), and the row number of the last visible row may be quite different in the table model. You can convert visible row numbers to model row numbers using tableSale.convertRowIndexToModel(). Which would make line 1039:
String idsale = (String) tableSale.getModel().getValueAt(
tableSale.convertRowIndexToModel(rcount - 1), 0);
In your code you initially check to see if there are any rows in the model. But at line 1037 you read the number of visible rows. If there is a RowSorter with a filter then this may return a value of 0 even if there are lots of rows in the model. Which would cause trouble here as well.

Java ArrayIndexOutOfBounds Exception -

I have 2 panels in my form which bound to a parent panel which has its layout set to card layout.
In the JFrame's constructor, a database operation is performed and data is taken and used to fill a JList.
Then when a user clicks on an item, a new panel ( as part of CardLayout ) shows up with a JTable filled with data taken from a database according to the selection made by the user in the listbox .
The program is basically a clinic management system.
In this JFrame, the cashier can see the id numbers of patients who are to pay their bills . These id numbers are displayed as a list in the JList.
On clicking the list, a patient id is selected and then the drugs prescribed are queried from the database and displayed in the table along with drug id & price.
The problem is that I get an ArrayOutOfBoundsException whenever I try to add a row to the JTable.
These are declared outside the mouseclick event (globally)
private Connection medDbConn = Connect("medicines.db");
private PreparedStatement mPst = null;
private ResultSet mRs = null;
private Connection conn = Connect("bills.db");
private PreparedStatement pst = null;
private ResultSet rs = null;
private ArrayList medicines_fine = new ArrayList();
private ArrayList medicines_fine_name = new ArrayList();
private ArrayList medicines_fine_qty = new ArrayList();
private ArrayList medicines_id = new ArrayList();
private ArrayList medicines_price = new ArrayList();
private ArrayList medicines_subtotal = new ArrayList();
private Double cf = 0.00;
/**
* Creates new form ViewBills
*/
private DefaultListModel listmodel;
private DefaultListModel model;
The following is executed in the mouseclick event of the JList .
// GET SELECTED VALUE FROM LIST
String listvalue = (String) jList1.getSelectedValue();
// SPLIT THE SELECTED LIST VALUE INTO ID AND DATETIME
String[] datas = listvalue.split("=");
// datas[0] = id and datas[1] = datetime
// STORE PATIENTID and DATETIME
String Patient_Id = datas[0].trim();
String DateTime = datas[1].trim();
String medicines_raw = null;
String[] medicines;
String[] keypair;
try {
// CONNECT THE DATABASE & PREPARE IT . THEN SET THE VALUES & FURTHER EXECUTE QUERY TO GET RESULT INTO "rs"
pst = conn.prepareStatement("SELECT CONSULTFEE,MEDICINES FROM VIEWBILLS WHERE ID=? AND DATETIME=?");
pst.setString(1, Patient_Id);
pst.setString(2, DateTime);
rs = pst.executeQuery();
// IF THERE IS A RECORD , THEN DO SOMETHING
if (rs.next()) {
cf = rs.getDouble("consultfee");
// GET THE RAW VALUE IN THE FORMAT Aspirin=12,sdsd=1,asdasd=2
medicines_raw = rs.getString("medicines");
// SPLIT THE WORD BY COMMAS AND STORE INTO ARRAY , SO EACH INDEX has Aspirin=12 kind of values
medicines = medicines_raw.split(",");
for (int i = 0; i < medicines.length; i++) {
medicines_fine.add(medicines[i]);
}
for (int i = 0; i < medicines_fine.size(); i++) {
keypair = medicines_fine.get(i).toString().split("=");
medicines_fine_name.add(keypair[0]);
System.out.println(keypair[0]);
System.out.println(keypair[1]);
medicines_fine_qty.add(keypair[1]);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
CardLayout cl = (CardLayout) Parent.getLayout();
cl.show(Parent, "card3");
// SECOND DATABASE CONNECTION STARTS HERE ...
for (int i = 0; i < medicines_fine_name.size(); i++) {
try {
pst = medDbConn.prepareStatement("SELECT ID,SELLPRICE FROM MEDICINES WHERE NAME=?");
pst.setString(1, (String) medicines_fine_name.get(i));
rs = pst.executeQuery();
if (rs.next()) {
medicines_id.add(rs.getString("id"));
medicines_price.add(rs.getDouble("sellprice"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
for ( int i = 0; i < medicines_fine_name.size() ; i++) {
tblmodel.addRow(new Object[] {medicines_id.get(i),medicines_fine_name.get(i),medicines_price.get(i),medicines_fine_qty.get(i)});
}
}
The whole thing sometimes run without error if the last for loop is removed . ( but that beats the purpose )
And Yeah , I said "sometimes" .. I am very much confused and as you can see, this code is written in a very ugly manner. I had written it the normal way, but this ArrayIndexOutOfBoundsException made me re-write the whole code 3 time, which ended in me writing pretty bad & ugly code but with the error still hanging on.
Pls let me know if anything is still unclear
Edit1: Basically what i'm trying to do is from the selected string in jlist , separate the datetime part and id part using split() function and store them to an array . Then use this id and name to select medicines from database . "medicines" is a string containing comma separated values like Aspirin=2,Amoxylin=5,etc=2,etc=10 where =10 means 10 of them ( indicating quantity . Then the drug name is stored into an arraylist and qty into another . Then use this medicine_name to get the medicine_id and sellprice. Finally set all this into a table .
The problem is here:
for ( int i = 0; i < medicines_fine_name.size() ; i++) {
tblmodel.addRow(new Object[] {medicines_id.get(i),medicines_fine_name.get(i),medicines_price.get(i),medicines_fine_qty.get(i)});
}
You are iterating over index in arraylist where there are no elements present.
What you are doing is you are firing two queries, in first query say you got 10 records.
Now in second query you iterate over your 10 records (processed and passed in arrayList from first query result) and fire in query 10 times. You may or may not get record and you do:
if (rs.next()) {
medicines_id.add(rs.getString("id"));
medicines_price.add(rs.getDouble("sellprice"));
}
if out of 10 you get record for 5 then size of medicines_id, medicines_price arraylist would be just 5.
Now comes your final loop as above. Here in the for loop you try to iterate over medicines_id,medicines_fine_name,medicines_price,medicines_fine_qty until size of 10 as per first query (medicines_fine_name.size()).
so when your i goes to index 6, you try to get on say
medicines_id.get(6)
but this element you never populated as per your second query hence ArrayIndexOutOfBoundException.
To fix this, one way would be to use else part to populate dummy value to id and price like below:
if (rs.next()) {
medicines_id.add(rs.getString("id"));
medicines_price.add(rs.getDouble("sellprice"));
} else {
medicines_id.add(rs.getString("9999"));
medicines_price.add(rs.getDouble("10.00"));
}

How do I show changes in my SQL table when I combined the values using GROUP BY?

I have this database table named Store_Data and I show three columns in the JTable.
Here are the columns:
NUMBERS
AMOUNT
DATE
How do I show the other columns in the jtable? The other columns are missing
I managed to obtain combined values using this SQL command, "SELECT NUMBERS, SUM(AMOUNT) FROM Store_Data GROUP BY NUMBERS", and I managed show it in the JTable.
However, In the JTable I only see the column NUMBERS and another column showing all the sum of the AMOUNT values. I don't see the other columns in the Jtable.
Here is my code,
private JTable showRecords(Connection con)
{
try
{
column.clear();
data.clear();
_stmt = con.createStatement();
//String getColumn = "SELECT * FROM APP.NYPMTRIPLESTRAIGHT";
/*this is only a test*/
String test = "SELECT NUMBERS, SUM(AMOUNT) FROM Store_Data GROUP BY NUMBERS";
ResultSet rs = _stmt.executeQuery(test);
//this will collect the data from the database
ResultSetMetaData metaData = rs.getMetaData();
//this will count all the columns from
int column_count = metaData.getColumnCount();
for(int j = 1; j <= column_count; j++)
{
column.add(metaData.getColumnName(j));
}
while(rs.next())
{
Vector<Object> vector = new Vector<Object>();
for(int i = 1; i <= column_count; i++)
{
vector.add(rs.getObject(i));
}
data.add(vector);
}
_records = new JTable(data, column);
return _records;
} catch (SQLException ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return _records;
}
NOTE: I know it is wrong to use Vector. I am only using it for testing.
Your query sums all the values of AMOUNT and displays the sum using a Group by clause.
Group by will group similar values into one entity based on the functions used. ["sum" in your case].
You need to get the numbers and amount from your database simply
SELECT NUMBERS, AMOUNT FROM APP.NYPMTRIPLESTRAIGHT;
then display the resultset data in your JTable.
Try this:
SELECT
t1.NUMBERS,
CONCAT(YEAR(T1.DATE) , '-' , MONTH(t1.DATE) , '-' ,DAY(t1.DATE)) as DATE,
SUM(AMOUNT) AS AMOUNT
FROM table1 t1
GROUP BY 1, 2
And here you have the sqlfiddle

Categories

Resources