data not added into vector variable - java

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.

Related

Updating dynamically JTable(s)

I'm working on a Java database application, where the user has one side to insert data and another to show in a JTable (in a JScrollPane) the content of the linked HSQLDB database. Everthing works so far so good, but I searched for a very long time without finding how to update my JTable dynamically when a change is made to the database (add, update or delete) for each instance of my program because several persons can work on it simultaneously.
It actually works by replacing my table model for local update, but for other instances, i have set a Timer which is not very clean.
Could you help me resolving this please ?
Here is my code (I have an Interface.java for "visible" part and a SQL.java to manage my db) :
My timer
JTable table = new JTable(sql.showTable("SELECT * FROM suivi_flotte"));
Timer timer = new Timer(900000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sql.updateTable();
nbLinesOrRefresh.setText("Actualisation...");
Timer timer2 = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nbLinesOrRefresh.setText("");
}
});
timer2.start();
timer2.setRepeats(false);
}
});
timer.setDelay(900000);
timer.start();
formatTable(table);
My updateTable() method (called each time there is an insert, update or delete)
protected void updateTable() {
Interface.f.table.setModel(showTable("SELECT * FROM suivi_flotte"));
Interface.f.formatTable(Interface.f.table); // a method to custom JTable appearance
}
My showTable(String query) method
protected DefaultTableModel showTable(String query) {
String[] columnsTitles = {"N°", "Propriétaire", "Service", "Grade", "Nom", "Prénom", "Mail", "N° SIM", "N° Tél", "Modèle", "N° Série", "IMEI", "N° Crypto", "Date début", "Date fin", "DS", "Commentaire", "Date de création"};
ArrayList<String> columnNames = new ArrayList<>();
ArrayList<Object> data = new ArrayList<>();
connectDB(); // only to connect to db
try (ResultSet rs = stmt.executeQuery(query)) {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.add(columnsTitles[i - 1]);
}
while (rs.next()) {
ArrayList<Object> row = new ArrayList<>(columns);
for (int i = 1; i <= columns; i++) {
row.add(rs.getObject(i));
}
data.add(row);
}
shutdownDB(); // to fully disconnect from db
} catch (SQLException e) {
System.out.println(e.getMessage());
}
Vector<Vector<?>> dataVector = new Vector<>();
Vector<String> columnNamesVector = new Vector<>();
for (int i = 0; i < data.size(); i++) {
ArrayList<?> subArray = (ArrayList<?>) data.get(i);
Vector<Object> subVector = new Vector<>();
for (int j = 0; j < subArray.size(); j++) {
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++) {
columnNamesVector.add(columnNames.get(i));
}
DefaultTableModel tModel = new DefaultTableModel(dataVector, columnNamesVector) {
private static final long serialVersionUID = 1L;
public Class<?> getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// tModel.fireTableDataChanged(); // <-- does not work
return tModel;
}
Thank you for your help.
UPDATE 1 :
All my connection/disconnection code :
private void connectDB() {
JFrame op = new JFrame();
op.setAlwaysOnTop(true);
try {
Class.forName("org.hsqldb.jdbcDriver");
co = DriverManager.getConnection("jdbc:hsqldb:file:db;shutdown=true");
stmt = co.createStatement();
} catch (SQLException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(op, "Erreur de connexion à la base de données :\n" + e.getMessage(), Interface.windowTitle, JOptionPane.ERROR_MESSAGE);
}
}
private void openDB() throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("db.sql"));
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
stmt.executeUpdate(sb.toString());
} catch (SQLException e) {}
}
private void shutdownDB() throws SQLException {
stmt.close();
co.close();
}
UPDATE 2 :
I changed everything in SQL.java to non-static. Each SQL.[...] has been changed to sql.[...] with private SQL sql = new SQL(); on top of the class and public SQL() {} in the class. I also changed it in the above code.

Refresh JScrollPane JTable Data on JPanel in JFrame

I wnat to fill my Table with new Datas which i get by my DataBase(MySQL). I get all datas and create a new Model with them, but if i want to refresh the specific panel, then it wont be repainted.
public class PanelWest extends JPanel implements ActionListener {
private JButton but_selectBP;
private JButton but_selectBPAdr;
private JButton but_selectGerichte;
private GroupLayout layoutGroup;
private Connector stmtExecuter = new Connector();
// private PanelCenter tableViewer = new PanelCenter();
public PanelWest() {
layoutGroup = createLayout();
this.setLayout(layoutGroup);
createButtons();
}
private GroupLayout createLayout() {
GroupLayout layout = new GroupLayout(this);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
return layout;
}
void createButtons() {
this.but_selectBP = new JButton("Kunden anzeigen");
this.but_selectBP.addActionListener(this);
this.but_selectBPAdr = new JButton("Gerichte anzeigen");
this.but_selectBPAdr.addActionListener(this);
this.but_selectGerichte = new JButton("Lieferanten anzeigen");
this.but_selectGerichte.addActionListener(this);
this.layoutGroup.setHorizontalGroup(layoutGroup.createParallelGroup().addComponent(but_selectBP).addComponent(but_selectBPAdr).addComponent(but_selectGerichte));
this.layoutGroup.setVerticalGroup(layoutGroup.createSequentialGroup().addComponent(but_selectBP).addComponent(but_selectBPAdr).addComponent(but_selectGerichte));
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src.equals(this.but_selectBP)) {
String query = "SELECT * FROM Kunde";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.setTableName("Kunde");
new PanelCenter().createTable(fillHeader(rst), fillData(rst));
}
if (src.equals(this.but_selectBPAdr)) {
String query = "SELECT * FROM Gericht";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.createTable(fillHeader(rst), fillData(rst));
}
if (src.equals(this.but_selectGerichte)) {
String query = "SELECT * FROM Lieferant";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.createTable(fillHeader(rst), fillData(rst));
}
}
private String[] fillHeader(ResultSet rst) {
try {
ResultSetMetaData rstMetaData = rst.getMetaData();
String[] header = new String[rstMetaData.getColumnCount()];
ArrayList<String> headerDetails = new ArrayList<>();
for (int i = 1; i <= rstMetaData.getColumnCount(); i++) {
headerDetails.add(rstMetaData.getColumnName(i));
}
int j = 0;
for(String head : headerDetails){
header[j] = head;
j++;
}
return header;
} catch (SQLException se) {
se.printStackTrace();
}
return null;
}
private Object[][] fillData(ResultSet rst) {
try {
ResultSetMetaData rstMetaData = rst.getMetaData();
int rowCount = 0;
rst.last();
rowCount = rst.getRow();
System.out.println(rowCount + " Rows");
rst.beforeFirst();
Object[][] data = new Object[rowCount][rstMetaData.getColumnCount()];
int row = 0;
while (rst.next()) {
for (int i = 0; i < rstMetaData.getColumnCount(); i++) {
data[row][i] = rst.getObject(i + 1);
}
row++;
}
return data;
} catch (SQLException se) {
System.out.println("Hier bei Fill");
}
return null;
}
}
I use remove, add revalidate and repaint on my jpanel.
void createTable(String[] header, Object[][] data) {
this.tableData = new JTable();
this.tableData.setModel(new MyTableModel(header, data));
this.tableData.setFillsViewportHeight(true);
this.tableData.addKeyListener(this);
this.scrollPaneTable = new JScrollPane(tableData);
this.scrollPaneTable.setSize(500, 500);
this.remove(this.scrollPaneTable);
this.add(this.scrollPaneTable);
this.revalidate();
this.repaint();
}
You don't need to reinitialize the table, table model.
Put some global variables on the top
private MyTableModel tableModel; //Your own table model
private JTable table;
Initialize them on init
public PanelWest() {
layoutGroup = createLayout();
this.setLayout(layoutGroup);
createButtons();
tableModel = new MyTableModel(header, data); //Your own tablemodel
table = new JTable(tableModel); //Hook the model to your table
this.add(table)
//...Do other things else to your table
}
Once you want to update the table, simply clear the rows from the table model and fill with new rows.
And ask JTable to update its data by calling
void createTable(String[] header, Object[][] data){
int cols = header.length;
int rows = data.length;
//Remove all rows from model
tableModel.setRowCount(0); //(As said by HovercraftFullOfEels)
Object[] row = new Object[cols];
for (int j = 0; j < data.length; j++){
for (int i = 0; i < cols; i++){
row[i] = data[j][i];
}
tableModel.addRow(row);
}
tableModel.fireTableDataChanged();
}
Hope it will help.
Thanks for your help.
I add a small test to my createTable method. I create a new window to show the new table datas and it works. i think my jpanel doesn't repaint correctly cause my grouplayout.
this.tableData = new JTable();
this.tableData.setModel(new MyTableModel(header, data));
this.tableData.setFillsViewportHeight(true);
this.tableData.addKeyListener(this);
this.scrollPaneTable = new JScrollPane(tableData);
this.scrollPaneTable.setSize(500, 500);
this.layoutGroup.setVerticalGroup(layoutGroup.createSequentialGroup().addComponent(this.scrollPaneTable, 400, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(this.scrollPaneChanges).addComponent(this.but_user).addComponent(this.but_dataChange));
// JFrame fr = new JFrame("Hello");
// fr.setLayout(null);
// fr.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// fr.setVisible(true);
// fr.add(this.scrollPaneTable);

Why Jtable Does not refresh from other class

I have the following cod!
when i call the fruitsTable() from refreshButton() it refreshes the JTable! but when i call it from another class it does not refresh the Table! bellow is the simplified code
public ResultSet sqlCommand(String sqlStatement) throws SQLException
{
this.sqlStatement = sqlStatement;
ConnectingToMysql fruitsConnection = new ConnectingToMysql();
Connection myConnection = fruitsConnection.ConnectingToMysql();
Statement st = myConnection.createStatement();
ResultSet result = st.executeQuery(sqlStatement);
return result;
}
public Vector<String> getColumnData() throws SQLException
{
ResultSetMetaData metaData = sqlCommand(sqlStatement).getMetaData();
int columnCount = metaData.getColumnCount();
Vector<String> allColumn = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
allColumn.add(metaData.getColumnName(i));
}
return allColumn;
}
public Vector<Vector<String>> getData() throws SQLException
{
ResultSet result = sqlCommand(sqlStatement);
ResultSetMetaData metaData = result.getMetaData();
int columnCount = metaData.getColumnCount();
Vector<Vector<String>> allRow = new Vector<Vector<String>>(columnCount);
while(result.next())
{
Vector<String> eachRow = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
eachRow.add(result.getString(i));
}
allRow.add(eachRow);
}
return allRow;
}
public JScrollPane fruitsTable() throws SQLException
{
Vector<String> columnData = getColumnData();
Vector<Vector<String>> rowData = getData();
fruitsTableModel.setDataVector(rowData,columnData);
Font font = new Font("Courier", Font.PLAIN,16);
fruitsTable = new JTable();
fruitsTable.setModel(fruitsTableModel);
fruitsTable.setPreferredScrollableViewportSize(new Dimension(850,310));
fruitsTable.setRowHeight(30);
fruitsTable.setFont(font);
JScrollPane fruitsScrollPane = new JScrollPane(fruitsTable);
dataValue();
return fruitsScrollPane;
}
private JButton refreshButton() throws SQLException
{
JButton refreshButton = new JButton("Refresh Record");
refreshButton.setPreferredSize(new Dimension(100,40));
refreshButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
fruitsTable();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
return refreshButton;
}
and this is the only code from the other class that calls the fruitsTable().
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
String number = numberTextField.getText();
int ID = Integer.parseInt(number);
String fruit = fruitTextField.getText();
String color = colorTextField.getText();
String taste = tasteTextField.getText();
System.out.println("The value is: " + number + " " + fruit + " " + color + " " + taste);
String sqlText = "Insert into fruits(ID,Fruit,Color,Tast) values(?,?,?,?)";
ConnectingToMysql connectingToMysql = new ConnectingToMysql();
Connection makeConnection = connectingToMysql.ConnectingToMysql();
PreparedStatement pdt = makeConnection.prepareStatement(sqlText);
pdt.setInt(1,ID);
if(fruit.isEmpty())
{
pdt.setNull(2,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(2,fruit);
}
if(color.isEmpty())
{
pdt.setNull(3,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(3,color);
}
if(taste.isEmpty())
{
pdt.setNull(4,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(4,taste);
}
pdt.executeUpdate();
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
}
catch(SQLIntegrityConstraintViolationException e)
{
JOptionPane.showMessageDialog(null, "The 'Number' you entered already exist!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e);
}
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
You're creating a new GetFruits object and refreshing it's table instead of updating the existing one. Try creating a class variable of GetFruits so you're using the same instance instead of creating a new one each time. Just guessing since I can't see all the code that contains the action listener.

How to edit row in JTable

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;
}

Implementing AbstractTableModel to JTable. How to add the methods?

I used to display my database data in a JTable and it was working fine. I found out that I need to implement AbstractTableModel or DefaultTableModel to update the data instantly.
I am not sure what I should write in getValueAt()? Where should I add fireDataChanged()? Any guidance is appreciated, thanks!
I used to retrieve my database data with this code:
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/watchlist","root","root");
String sql = "SELECT * FROM watchlist";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i));
}
int rowCount = md.getColumnCount();
while (rs.next())
{
Vector row = new Vector(rowCount);
for (int i=1; i <= rowCount; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
My AbstractTableModel:
public class MyTableModel extends AbstractTableModel
{
Vector columnNames = new Vector();
Vector data = new Vector();
public void connectionDB()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/watchlist","root","root");
String sql = "SELECT * FROM watchlist";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
}
catch(Exception e)
{
System.out.println(e);
}
}
public int getColumnCount()
{
return columnNames.size();
}
public int getRowCount()
{
return data.size();
}
public Object getValueAt()
{
return data;
}
public boolean isCellEditable(int row, int col)
{
return false;
}
}
Here is a sample of using AbstractTableModel:
public class CustomTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private static final String[] columnNames = new String[]{"ID", "Name", "Number", "Yes/No"};
protected List<Foo> lstFoo;
protected Class<?>[] types = new Class[]{Integer.class, String.class, String.class, Boolean.class};
public CustomTableModel(List<Foo> lstFoo)
{
this.lstFoo = lstFoo;
fireTableDataChanged();
}
#Override
public String getColumnName(int columnIndex)
{
return columnNames[columnIndex];
}
#Override
public Class<?> getColumnClass(int columnIndex)
{
return types[columnIndex];
}
#Override
public boolean isCellEditable(int row, int columnIndex)
{
return false;
}
#Override
public Object getValueAt(int row, int column)
{
if(row < 0 || row >= lstFoo.size()) return null;
Foo obj = lstFoo.get(row);
switch(column)
{
case 0: return obj.getId();
case 1: return obj.getName();
case 2: return obj.getNumber();
case 3: return obj.isYes();
default: return null;
}
}
#Override
public int getRowCount()
{
return lstFoo.size();
}
#Override
public int getColumnCount()
{
return columnNames.length;
}
}
just one point, two many connections to a database will reduce the speed and too much overhead. I had this issue and was able to solve it.

Categories