Hello when I delete a product from database through a table using a popupMenu (Right click Button) the row still shows up in the table list, the insertProduct method is working fine and inserts the row to table but the removeProduct method doesn't work can you tell me where is the problem in my code please ?
ProductTable.java:
public class ProductTable extends AbstractTableModel {
ProductsDao pd = new ProductsDao();
private final List<Products> products;
public ProductTable() throws Exception {
this.patients = (ArrayList<Products>) pd.getProductsList();
}
private String[] columnNames = {"PRODUCT NAME", "PRODUCT CATEGORY", "PRODUCT PRICE"};
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
#Override
public int getRowCount() {
return products.size();
}
#Override
public Object getValueAt(int row, int column) {
Products p = products.get(row);
switch (column)
{
case 0: return p.getProductName();
case 1: return p.getProductCategory();
case 2: return p.getProductPrice();
}
}
#Override
public void setValueAt(Object value, int row, int column) {
Products p = products.get(row);
switch (column) {
case 0: p.setProductName((String)value); break;
case 1: p.setProductCategory((Date)value); break;
case 2: p.setProductPrice((int)value); break;
}
fireTableCellUpdated(row, column);
}
public Products getProduct(int row) {
return products.get(row);
}
public void addProduct(Products p) {
insertProduct(getRowCount(), p);
}
public void insertProduct(int row, Products p) {
products.add(row, p);
fireTableRowsInserted(row, row);
}
public void deleteProduct(Products p) {
removeProduct(getRowCount(), p);
}
public void removeProduct(int row, Products p) {
products.remove(row);
fireTableRowsDeleted(row, row);
}
}
JFrame :
public void popupTable() {
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuItem1 = new JMenuItem("Delete", new ImageIcon(getClass().getResource("")));
menuItem1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int row = jTable1.getSelectedRow();
String cell = jTable1.getModel().getValueAt(row, 0).toString();
Products p = new Products();
p.setId(cell);
try {
int count = ProductsDao.getInstance().delete(p);
if (count == 1) {
removeRowFromTable(p);
JOptionPane.showMessageDialog(null, "Deleted");
} else {
JOptionPane.showMessageDialog(null, "Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
});
popupMenu.add(menuItem1);
jTable1.setComponentPopupMenu(popupMenu);
}
public static void removeRowFromTable(Products data) {
ProductTable t = (ProductTable) jTable1.getModel();
t.deleteProduct(data);
}
ProductsDao.java:
#Override
public List<Products> getProductsList() throws Exception {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Products> products = new ArrayList<Products>();
try {
con = getConnection();
String sql = "SELECT * FROM products ORDER BY PRODUCT_ID DESC";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Products product = new Products();
product.setProductName(rs.getString("PRODUCT_NAME"));
product.setProductCategory(rs.getString("PRODUCT_CATEGORY"));
product.setProductPrice(rs.getInt("PRODUCT_PRICE"));
products.add(product);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
} finally {
rs.close();
ps.close();
closeConnection(con);
}
return products;
}
These methods don't make sense I'm afraid:
public void deleteProduct(Products p) {
removeProduct(getRowCount(), p);
}
public void removeProduct(int row, Products p) {
products.remove(row);
fireTableRowsDeleted(row, row);
}
since you never really use the Products parameter, p, in any useful way to identify where it is in the table model. Also, I'm not really sure why you have two methods, and what they are each supposed to represent.
Instead, assuming that products in your TableModel is an ArrayList<Products>, and assuming that you've overridden Products equals and hashCode methods appropriately, you need to find the index of the selected item in the list and then remove it from the list and notify the listeners that this has been performed. Something like:
public void deleteProduct(Products p) {
int row = products.indexOf(p);
products.remove(row);
fireTableRowsDeleted(row, row);
}
This will only work if you override equals and hashCode correctly for Products.
sorry but I still don't get this thing from my database dont change to check box. it just show as true or false
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM tblpdareenlist");
DefaultTableModel model = (DefaultTableModel) viewRecordTable.getModel();
int x = 0;
String b, c, d, e, f, g, h, i;
Boolean a;
while (rs.next()) {
a = rs.getBoolean("colAttend");
b = rs.getString("colNr");
c = rs.getString("colRank");
d = rs.getString("colFName");
e = rs.getString("colMName");
f = rs.getString("colLName");
g = rs.getString("colSN");
h = rs.getString("colUnit");
i = rs.getString("colETE");
model.insertRow(x, new Object[]{a,b,c,d,e,f,g,h,i});
x++;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, "Syntax Error\n" + e);
}
The JTable will display a check box for a column if the table model's getColumnClass method returns Boolean.class for that column[1]. You are using the DefaultTableModel which only returns Object.class for any column. This model is just a very simple model, not the best for a real system, more for testing or very simple data.
The best is to implement your own TableModel returning the correct class for given column, e.g. extending the AbstractTableModel.
For testing only you can just extend the DefaultTableModel and override the getColumnClass method:
var model = new DefaultTableModel(0, 3) {
#Override
public Class<?> getColumnClass(int col) {
if (col == 0) return Boolean.class;
else return super.getColumnClass(col);
}
};
var table = new JTable(model);
model.insertRow(0, List.of(false, "false", 0).toArray());
model.insertRow(1, List.of(true, "true", 1).toArray());
JOptionPane.showMessageDialog(null, table);
Again, on the long run, for a real project, you will get stuck very soon with that solution - much better to implement a dedicated TableModel. A very simple (incomplete) example:
public static void main(String[] args) {
var model = new MyTableModel();
var table = new JTable(model);
model.add(new MyData(false, "false", 0));
model.add(new MyData(true, "true", 1));
JOptionPane.showMessageDialog(null, table);
}
static final int FLAG = 0;
static final int NAME = 1;
static final int VALUE = 2;
private static class MyTableModel extends AbstractTableModel {
private final List<MyData> list = new ArrayList<>();
void add(MyData data) {
list.add(data);
}
#Override
public int getRowCount() {
return list.size();
}
#Override
public int getColumnCount() {
return 3;
}
#Override
public Object getValueAt(int row, int col) {
var data = list.get(row);
switch(col) {
case FLAG: return data.flag;
case NAME: return data.name;
case VALUE: return data.value;
}
throw new IllegalArgumentException("column " + col);
}
#Override
public Class<?> getColumnClass(int col) {
switch(col) {
case FLAG: return Boolean.class;
case NAME: return String.class;
case VALUE: return Integer.class;
}
throw new IllegalArgumentException("column " + col);
}
}
private static class MyData {
final boolean flag;
final String name;
final int value;
MyData(boolean flag, String name, int value) {
this.flag = flag;
this.name = name;
this.value = value;
}
}
[1] JTable Tutorial
the vector variable that can't fetch element from another vector variable.
public class DealerView_GUI extends javax.swing.JInternalFrame {
/**
* Creates new form DealerView
*/
String s;
private Vector<Vector<String>> data;
private Vector<String> header;
DB db = new DB();
public DealerView_GUI() {
String[][] dfg = null;
Connection con = db.getConnection();
ResultSet rs = null;
Object[][] dataR = null;
try
{
PreparedStatement ps = con.prepareStatement("SELECT * FROM TEMP_TBL");
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
int cv = 0;
while(rs.next())
{
Vector<String> row = new Vector<String>(columns);
String s = rs.getString("FIRST_NAME");
for (int i = 1; i <= columns; i++) {
row.addElement(s);
}
data.addElement(row);
cv++;
}
header = new Vector<String>();
header.add("Dealer Id");
header.add("Dealer Name");
header.add("Phone");
header.add("Place");
header.add("Paid Amount");
header.add("Unpaid Amount");
}
catch(SQLException ex)
{
LogManager.logErr(ex);
}
initComponents();
DefaultTableModel dm;
dm = (DefaultTableModel)serachedDealer_jTable.getModel();
serachedDealer_jTable.setModel(new javax.swing.table.DefaultTableModel(data,header){
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
}
}
the error shows in run time for the line of 'data.addElement(row);'.
the vector variable(data) shows the null pointer exception.
You didn't allocate the variable data and it is null.
Allocate the memory by writing data = new Vector<>(); on the first line of the constructor.
I'm following this example code to create my own tableModel class to display data from a db using cachedRowSet, and use rowSetEvent to refresh the table when insert a row and delete a row to the cachedRowSet.
https://github.com/abissell/jdbctutorial/blob/master/src/com/oracle/tutorial/jdbc/CoffeesTableModel.java
public void rowChanged(RowSetEvent event) {
try {
tm.rs.moveToCurrentRow();
tm = new MyTableModel(tm.rs); // to get right row nums
table.setModel(tm);
} catch (SQLException er) {
er.printStackTrace();
}
}
public class MyTableModel extends AbstractTableModel {
CachedRowSet rs;
ResultSetMetaData meta;
int cols, rows;
public MyTableModel(CachedRowSet r) {
rs = r;
try {
meta = rs.getMetaData();
cols = meta.getColumnCount();
rs.beforeFirst();
rows = 0;
while (rs.next()) {
rows++;
}
rs.beforeFirst();
} catch(SQLException e) {
e.printStackTrace();
}
}
public void insert(String[] info) {
try {
rs.moveToInsertRow();
for(int i = 0;i < cols;i++) {
rs.updateString(i+1, info[i]);
}
rs.insertRow();
rs.moveToCurrentRow();
} catch(SQLException e) {
e.printStackTrace();
}
}
public void delete(int id) {
try {
rs.beforeFirst();
while(rs.next()) {
if(Integer.parseInt(rs.getString(1))==id) {
rs.deleteRow();
break;
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
#Override
public int getRowCount() {
return rows;
}
#Override
public int getColumnCount() {
return cols;
}
#Override
public String getColumnName(int col) {
try {
return meta.getColumnLabel(col + 1);
} catch (SQLException e) {
return e.toString();
}
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
try {
if (!rs.absolute(rowIndex + 1)) {
return null;
}
rs.absolute(rowIndex + 1);
Object o = rs.getObject(columnIndex + 1);
if (o == null) {
return null;
} else {
return o.toString();
}
} catch (SQLException e) {
e.printStackTrace();
return e.toString();
}
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
}
con = DriverManager.getConnection(url);
st = con.prepareStatement("SELECT id,name,sex,age,cell FROM PATIENTS");
rs = st.executeQuery();
crs = new CachedRowSetImpl();
crs.setType(ResultSet.TYPE_SCROLL_SENSITIVE);
crs.setConcurrency(ResultSet.CONCUR_UPDATABLE);
crs.populate(rs);
tm is the tableModel.
The table will refresh immediately after a row deleted from the cachedRowSet, but when i insert a new row into cachedRowSet, then the table can't show the newly added row immediately. And i checked the rowChanged() been called and the row inserted inside the db.
Even tried to refetch the table data each time or repaint() still not working. I couldn't figure out why.
Maybe cause swing process racing then it can't refresh immediately? I just opened another JFrame to fill out the data and then insert.
Also, what if i use the resultSet directly inside the model? Will the table automatically updated when you insert a row in the db if i didn't close the connection. Or it's just used to get the initial data and you have to run query again to refresh.
Thank you
=================update==================
I tried to change the table model to use ArrayList to store and update db results, then the insert will be update the table immediately. Maybe cause cachedRowSet update slower?
Confused, don't know why.
I have seen similar questions here, on the stackoverflow but anyway I couldn't resolve my problem with these answers.
What i would like to do:
click double on cell in the JTable (which is editable thanks to isCellEditable method)
save new value of a cell in my custom TableModel to print this new value
update data in my database (SQlite)
What I have done:
this is my custom TableModel
.
import javax.swing.table.AbstractTableModel;
public class KierunkiTableModel extends AbstractTableModel {
private boolean DEBUG = false;
private String[] columnNames = { "Id", "Data Wstawienia",
"Data Modyfikacji", "Kierunek", "Opis" };
private Object[][] data = DodEdKierunki.populateData(DodEdKierunki.count);
#Override
public int getRowCount() {
return data.length;
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public boolean isCellEditable(int row, int col) {
return true;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
#Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
this is my JPanel where I print my JTable:
.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import baza.danych.DBConnector;
public class DodEdKierunki extends JPanel implements ActionListener {
private JButton dodaj;
private JButton edytuj;
private JButton next;
private JButton previous;
static JTable table;
static Object[][] data = new Object[1][5];
static int count = setValue();
public DodEdKierunki() {
dodaj = new JButton("Dodaj");
edytuj = new JButton("Edytuj");
next = new JButton("Pokaż kolejne 5");
previous = new JButton("Pokaż poprzednie 5");
setLayout(new FlowLayout());
dodaj.addActionListener(this);
edytuj.addActionListener(this);
next.addActionListener(this);
previous.addActionListener(this);
add(dodaj);
add(edytuj);
add(next);
add(previous);
table = new JTable(new KierunkiTableModel());
table.setFillsViewportHeight(true);
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(130);
table.getColumnModel().getColumn(4).setPreferredWidth(130);
table.setEnabled(true);
add(table.getTableHeader(), BorderLayout.PAGE_START);
add(table, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == dodaj) {
new DodajKierunekFrame();
} else if (source == edytuj) {
new EdytujKierunekJFrame();
} else if (source == next) {
DBConnector db = new DBConnector();
int id = db.getHighestID("Kierunki");
int currId = count + 5;
if (currId <= id) {
count = count + 5;
data = populateData(count);
KierunkiTableModel model = new KierunkiTableModel();
model.fireTableDataChanged();
table.setModel(model);
setLayout(new FlowLayout());
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(130);
table.getColumnModel().getColumn(2).setPreferredWidth(130);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(130);
table.repaint();
db.closeConnection();
}
} else if (source == previous) {
if (count > 5) {
count = count - 5;
data = populateData(count);
KierunkiTableModel model = new KierunkiTableModel();
model.fireTableDataChanged();
table.setModel(model);
setLayout(new FlowLayout());
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(130);
table.getColumnModel().getColumn(2).setPreferredWidth(130);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(130);
table.repaint();
}
}
}
static Object[][] populateData(int count) {
DBConnector db = new DBConnector();
Object[][] lista = db.selectKierunki(count, "Kierunki");
db.closeConnection();
return lista;
}
private static int setValue() {
DBConnector db = new DBConnector();
int value = db.getHighestID("Kierunki");
db.closeConnection();
return value;
}
}
My problem is: I can edit a cell but I don't know how to save this changes. So my question is: How to change data model after editing a row in JTable ?
I have read http://download.oracle.com/javase/tutorial/uiswing/components/table.html
Try this
Use DefaultTableModel if you are not
if(ae.getSource()==update){
int row=table.getSelectedRow();
int n=JOptionPane.showConfirmDialog(mainPanel, "Would you like to update the record?", "Confirm", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
try{
Connection con=null;
Statement st=null;
ResultSet rs=null;
ResultSet rs1=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/db.accdb";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop");
st=con.createStatement();
rs=st.executeQuery("select * from Credit where TID="+table4.getValueAt(row, 3));
if(rs.next()){
s1=rs.getString(1);
s2=rs.getString(2);//accounno
s3=rs.getString(3);//name
s4=rs.getString(4);
s5=rs.getString(5);//paid
s6=rs.getString(6);//unpaid
}
PreparedStatement smt=con.prepareStatement("select * from Debit where Name=?");
smt.setObject(1, s3);
rs=smt.executeQuery();
if(rs.next()){
u1=rs.getString(1);
u2=rs.getString(2);
u3=rs.getString(3);
u4=rs.getString(4);
u5=rs.getString(5);
u6=rs.getString(6);//unpaid
}
st.executeUpdate("delete from Credit where TID="+table4.getValueAt(row,3));
st.executeUpdate("delete from Debit where Name='"+s3+"'");
tid=Integer.parseInt(table4.getValueAt(row, 3).toString());
date=table.getValueAt(row, 0).toString();
jama=table.getValueAt(row, 1).toString();//s5
baki=table.getValueAt(row, 2).toString();//s6
nett=table4.getValueAt(row, 4).toString();
rs1=st.executeQuery("select * from NettDate where Name='"+s3+"'");
while(rs1.next()){
nettdate=rs1.getString(2);
nettbal=rs1.getString(3);
}
String tpaid=Integer.toString(Integer.parseInt(s5)-Integer.parseInt(jama));
String tunpaid=Integer.toString(Integer.parseInt(s6)-Integer.parseInt(baki));
if(u6.contains("-")){
System.out.println("Contains -");
if(tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("1-"+tupdate);
}else if(!tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("2-"+tupdate);}
else if(tpaid.contains("-")&!tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("3-"+tupdate);
}else{
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("4-"+tupdate);
}
}else{
System.out.println("Not Contains -");
if(tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("1"+tupdate);
}else if(!tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("2"+tupdate);}
else if(tpaid.contains("-")&!tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("3"+tupdate);
}else{
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("4"+tupdate);
}
}
// tupdate=Integer.toString(Integer.parseInt(a)+Integer.parseInt(paid)-Integer.parseInt(unpaid));
// }else{
// tupdate=Integer.toString(Integer.parseInt(a)-Integer.parseInt(paid)+Integer.parseInt(unpaid));
// }
int i=st.executeUpdate("insert into Credit values("+tid+",'"+s2+"','"+s3+"','"+date+"','"+jama+"','"+baki+"','"+nett+"')");
st.executeUpdate("insert into Debit values('"+s2+"','"+s3+"','"+u3+"','"+u4+"','"+date+"','"+tupdate+"')");
//if(Integer.parseInt(table.getValueAt(row, 4).toString())==1){
if(Integer.parseInt(table4.getValueAt(row, 4).toString())==1){
st.executeUpdate("delete from NettDate where Name='"+s3+"'");
st.executeUpdate("insert into NettDate values('"+s3+"','"+date+"','"+nettb+"')");
}
if(i==0){
String msg="Record not updated Successfully";
String ss="Sorry..........";
int res=JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog((Component) null,msg,ss,res);
}else{
String msg="Record updated Successfully";
String ss="Congratlations..........";
int res=JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog((Component) null,msg,ss,res);
//dispose();
}
jComboBox.requestFocusInWindow();
model.setRowCount(0);
model1.setRowCount(0);
model2.setRowCount(0);
b=0;
a=0;
tj="0";
tb="0";
t=0;
gt="0";
an="0";nam="0";mono="0";cit="0";
DBEngine dbengine = new DBEngine();
data = dbengine.getJamaCustomer(s3);
Object[] d3={data1.get(0).get(0),data1.get(0).get(1),data1.get(0).get(3),data1.get(0).get(4)};
model1.addRow(d3);
JTable table5=new JTable(data,header3);
for(int i2=0;i2<table5.getRowCount();i2++){
Object[] d={data.get(i2).get(0),data.get(i2).get(1),data.get(i2).get(2),data.get(i2).get(3),data.get(i2).get(4)};
model2.addRow(d);
}
JTable table1=new JTable(data,header);
for(int i1=0;i1<table1.getRowCount();i1++){
Object[] d={data.get(i1).get(0),data.get(i1).get(1),data.get(i1).get(2)};//,data.get(i).get(3),data.get(i).get(4)};
model.addRow(d);
}
for(int i2=0;i2<table1.getRowCount();i2++){
a=a+Integer.parseInt(data.get(i2).get(1));
b=b+Integer.parseInt(data.get(i2).get(2));
}
tj=Integer.toString(a);
tb=Integer.toString(b);
Object[] d1={"Total",tj,tb};//,"",""};
Object[] d11={"Total",tj,tb,"",""};
model.addRow(d1);
model2.addRow(d11);
t=Integer.parseInt(tb)-Integer.parseInt(tj);
gt=Integer.toString(t);
Object[] d2={"Nett Balance","",gt};//,"",""};
Object[] d21={"Nett Balance","",gt,"",""};
model.addRow(d2);
model2.addRow(d21);
jlab7.setText(gt);
tablePanel.repaint();
con.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ManageCustomer.class.getName()).log(Level.SEVERE, null, ex);
}catch(Exception err){
System.out.println("GG Yes"+err);
}
} else if (n == JOptionPane.NO_OPTION) {
try {
Connection con=null;
Statement st=null;
ResultSet rs=null;
// ResultSet rs1=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/Program Files/Shop/shop.accdb";
//userID = "Admin";
password = "3064101991";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
st = con.createStatement();
//rs=st.executeQuery("select * from Credit where TID="+table.getValueAt(row, 0));
rs=st.executeQuery("select * from Credit where TID="+table4.getValueAt(row, 3));
if(rs.next()){
s1=rs.getString(1);
s2=rs.getString(2);//accounno
s3=rs.getString(3);//name
s4=rs.getString(4);
s5=rs.getString(5);//paid
s6=rs.getString(6);//unpaid
}
model.setRowCount(0);
model1.setRowCount(0);
model2.setRowCount(0);
b=0;
a=0;
tj="0";
tb="0";
t=0;
gt="0";
an="0";nam="0";mono="0";cit="0";
DBEngine dbengine = new DBEngine();
data = dbengine.getJamaCustomer(s3);
Object[] d3={data1.get(0).get(0),data1.get(0).get(1),data1.get(0).get(3),data1.get(0).get(4)};
model1.addRow(d3);
JTable table5=new JTable(data,header3);
for(int i2=0;i2<table5.getRowCount();i2++){
Object[] d={data.get(i2).get(0),data.get(i2).get(1),data.get(i2).get(2),data.get(i2).get(3),data.get(i2).get(4)};
model2.addRow(d);
}
JTable table1=new JTable(data,header);
for(int i1=0;i1<table1.getRowCount();i1++){
Object[] d={data.get(i1).get(0),data.get(i1).get(1),data.get(i1).get(2)};//,data.get(i).get(3),data.get(i).get(4)};
model.addRow(d);
}
for(int i2=0;i2<table1.getRowCount();i2++){
a=a+Integer.parseInt(data.get(i2).get(1));
b=b+Integer.parseInt(data.get(i2).get(2));
}
tj=Integer.toString(a);
tb=Integer.toString(b);
Object[] d1={"Total",tj,tb};//,"",""};
Object[] d11={"Total",tj,tb,"",""};
model.addRow(d1);
model2.addRow(d11);
t=Integer.parseInt(tb)-Integer.parseInt(tj);
gt=Integer.toString(t);
Object[] d2={"Nett Balance","",gt};//,"",""};
Object[] d21={"Nett Balance","",gt,"",""};
model.addRow(d2);
model2.addRow(d21);
jlab7.setText(gt);
tablePanel.repaint();
jComboBox.requestFocusInWindow();
// rs=st.executeQuery("select TID,Date,Paid,Unpaid,Nett from Credit where Name='"+s3+"' order by Date");
// table.setModel(buildTableModel(rs));
con.close();
//pstmt.close();
JOptionPane.showMessageDialog((Component) null,"You choose not to update the data !");
}catch (ClassNotFoundException err) {
// System.out.println(e);
err.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex);
}
}
}//end btn1
public Vector getJamaCustomer(Object name)throws Exception
{
Vector<Vector<String>> jamacustomerVector = new Vector<Vector<String>>();
Connection conn = dbConnection();
PreparedStatement pre = conn.prepareStatement("select * from Credit where Name='"+name+"' order by TID");
ResultSet rs = pre.executeQuery();//
while(rs.next())
{
Vector<String> jamacustomer = new Vector<String>();
//jamacustomer.add(rs.getString(2)); //Empid
jamacustomer.add(rs.getString(4)); //Empid
jamacustomer.add(rs.getString(5)); //Empid
jamacustomer.add(rs.getString(6)); //Empid
jamacustomer.add(rs.getString(1)); //Empid
jamacustomer.add(rs.getString(7)); //Empid
jamacustomerVector.add(jamacustomer);
}
/*Close the connection after use (MUST)*/
if(conn!=null)
conn.close();
return jamacustomerVector;
//return bakicustomerVector;
}