how update JTable after adding a row into database

how update JTable after adding a row into database

J have two classes, listed below, one is table model, and second show data from database in JTable, and it's OK, but after adding a row into database table does't update. How update JTable after adding a row into database?

package djile pak.java clss.for_table;

/**
    Class which creates table model
*/

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class ModelDataTabele extends AbstractTableModel {
    private String[] columnNames;
    private Object[][] data;
    private boolean edit table, change data;

public ModelDataTabele(String[] naziviKolona, Object[][] podaci) {
    columnNames = naziviKolona;
    data = podaci;
    edit_table = tedit;
    change_data = dchange;
}

public void tableChanged() {
    fireTableDataChanged();
}

public int getColumnCount() {
    return columnNames.length;
}

public int getRowCount() {
    return data.length;
}

public String getColumnName(int col) {
    return columnNames[col];
}

public Object getValueAt(int row, int col) {
    return data[row][col];
}

public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
}

public boolean isCellEditable(int row, int col) {
    if (col < 2) {
        return false;
    } else {
        return true;
    }
}

public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
}

public void insertRow(int row, Object[] npodaci) {
    for(int i = 0; i < npodaci.length; i++) {
        data[row][i] = npodaci[i];
    }
}

}

// Form which shows data in JTable from database
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.event.*;
import java.sql.*;

import djile pak.java clss.for_screen.*;
import djile pak.java clss.for_table.*;
import djile pak.java clss.for_mysql.*;

public class DodajDlg extends JDialog implements ActionListener, FocusListener, KeyListener {

JPanel gornjiPanel = new JPanel();
JPanel centralniPanel = new JPanel();
JPanel donjiPanel = new JPanel();
JScrollPane zaTabelu;
JLabel lblAutor = new JLabel("IME I PREZIME AUTORA: ");
JTextField txtAutor = new JTextField(100);
JButton btnPotvrdi = new JButton("Potrdi");
JButton btnOdustani = new JButton("Odustani");
JTable tabela;
ModelDataTabele mdt;
TableColumn kolona;
ConnectMySQL vezaDB;
Connection Konekcija;
Statement sqlKomanda;
String upit;
ResultSet rs;
String[] nazivi;
Object[][] podaci;
private static int dodajsta;
boolean odustani = false;
static String[] parametri_vb;
int[] wih;

int rb, idna;
String naziva;

public DodajDlg(String naslov, int stasedodaje, String[] parametri_veze) {

    dodajsta = stasedodaje;
    parametri_vb = parametri_veze;

    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setTitle(naslov);

    int w = 0, h =0, koeficijent_w = 100, koeficijent_h = 100;
    PutFrameTo width_height  = new PutFrameTo(w, h);
    wih = width_height.Scr_WH();
    switch (dodajsta) {
        case 1:
        case 2:
            koeficijent_w = 95;
            koeficijent_h = 95;
            break;
    }
    w = (wih[0] / 100) * koeficijent_w;
    h = (wih[1] / 100) * koeficijent_h;
    setSize(w, h);

    PutFrameTo pozicija = new PutFrameTo(w, h);
    int[] xiy = pozicija.XY_Pos();

    setResizable(false);
    setLocation(xiy[0], xiy[1]);
    setModal(true);

    gornjiPanel.setBackground(Color.lightGray);
    switch (dodajsta) {
        case 1:

            break;
        case 2:
            this.formaAutor();
            break;
    }
    add(gornjiPanel, BorderLayout.NORTH);

    btnPotvrdi.setMnemonic(KeyEvent.VK_P);
    btnPotvrdi.setEnabled(false);
    btnOdustani.setMnemonic(KeyEvent.VK_O);
    btnOdustani.setEnabled(true);

    btnPotvrdi.addActionListener(this);
    btnPotvrdi.addFocusListener(this);
    btnPotvrdi.addKeyListener(this);
    btnOdustani.addActionListener(this);
    btnOdustani.addFocusListener(this);
    btnOdustani.addKeyListener(this);

    centralniPanel.setBackground(Color.lightGray);
    centralniPanel.add(btnPotvrdi);
    centralniPanel.add(btnOdustani);
    add(centralniPanel, BorderLayout.CENTER);

    napraviTabelu();

    donjiPanel.setBackground(Color.darkGray);
    zaDonjiPanel();
    add(donjiPanel, BorderLayout.SOUTH);

    setVisible(true);
}

public void napraviTabelu() {
    switch (dodajsta) {
        case 1:

            break;
        case 2:
            int sirinaID = (wih[0] / 100) * 10;
            int brslogova = brojSlogova();
            nazivi = new String[3];
            nazivi[0] = "RB";
            nazivi[1] = "ID";
            nazivi[2] = "Autor";
            if (brslogova == 0) {
                podaci = new Object[1][3];
                podaci[0][0] = 1;
                podaci[0][1] = 0;
                podaci[0][2] = "";
            } else {
                podaci = new Object[brslogova][3];
                procitajPodatke();
            }
            mdt = new ModelDataTabele(nazivi, podaci);
            tabela = new JTable(mdt);
            for (int j = 0; j < tabela.getColumnCount(); j++) {
                kolona = tabela.getColumnModel().getColumn(j);
                if (j == 0) {
                    kolona.setPreferredWidth(50);
                } else if (j == 1) {
                    kolona.setPreferredWidth(sirinaID);
                } else {
                    kolona.setPreferredWidth(wih[0] - (sirinaID + 50));
                }
            }
            break;
    }
}

private void formaAutor() {

    txtAutor.setToolTipText("Upisati IME i PREZIME autora");
    txtAutor.addKeyListener(this);

    gornjiPanel.add(lblAutor);
    gornjiPanel.add(txtAutor);
}

public void actionPerformed(ActionEvent event) {
    Object akter = event.getSource();
    if (akter == btnOdustani) {
        dispose();
    }

    if (akter == btnPotvrdi) {
        pozoviUpis();
        napraviTabelu();

    }

}

private void zaDonjiPanel() {
    int sirina = 0;
    int visina = 0;

    switch (dodajsta) {
        case 1:

            break;
        case 2:
            sirina = (wih[0] / 100) * 93;
            visina = (wih[1] / 100) * 75;
            break;
    }
    Font zaglavljeFont = new Font("DialogInput", Font.BOLD, 15);
    tabela.getTableHeader().setFont(zaglavljeFont);
    zaTabelu = new JScrollPane(tabela);
    zaTabelu.setPreferredSize(new Dimension(sirina, visina));
    tabela.setFillsViewportHeight(true);
    tabela.setSelectionForeground(Color.white);
    tabela.setSelectionBackground(Color.blue);
    tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    donjiPanel.add(zaTabelu);
}

private int brojSlogova() {
    int brojsl = 0;
    if (poveziSeSaBazom()) {
        switch (dodajsta) {
            case 1:

                break;
            case 2:
                try {
                    sqlKomanda = Konekcija.createStatement();
                    upit = "select count(*) from autor";
                    rs = null;
                    rs = sqlKomanda.executeQuery(upit);
                    if (rs != null) {
                        rs.next();
                        brojsl = rs.getInt(1);
                    }
                    rs.close();
                    sqlKomanda.close();
                } catch (SQLException esql) {
                    String poruka = "Gre\u0161ka: " + esql.toString() + "\n" + esql.getMessage();
                    JOptionPane.showMessageDialog(null, poruka, "Gre\u0161ka", JOptionPane.WARNING_MESSAGE);
                }
                vezaDB.prekiniVezuSaBazom(Konekcija);
                break;
        }
    }
    return brojsl;
}

private void pozoviUpis() {
    if (poveziSeSaBazom()) {
        upisiUBazu();
        vezaDB.prekiniVezuSaBazom(Konekcija);
    }else {
        JOptionPane.showMessageDialog(null, "PODACI NISU UPISANI!", "Gre\u0161ka", JOptionPane.WARNING_MESSAGE);
    }
}

private boolean poveziSeSaBazom() {
    vezaDB = new ConnectMySQL();
    Konekcija = vezaDB.konekcijaSaBazom(parametri_vb[0], parametri_vb[1], parametri_vb[2], parametri_vb[3]);
    if (Konekcija != null) {
        return true;
    } else {
        return false;
    }
}

private void upisiUBazu() {
    switch (dodajsta) {
        case 1:

            break;
        case 2:
            try {
                sqlKomanda = Konekcija.createStatement();
                upit = "insert into autor(ida, autor) values(?,?)";
                PreparedStatement upisi = Konekcija.prepareStatement(upit);
                upisi.setInt(1, 0);
                upisi.setString(2,  txtAutor.getText());
                upisi.executeUpdate();
                upisi.close();
                sqlKomanda.close();
            } catch (SQLException esql) {
                String poruka = "Gre\u0161ka: " + esql.toString() + "\n" + esql.getMessage();
                JOptionPane.showMessageDialog(null, poruka, "Gre\u0161ka", JOptionPane.WARNING_MESSAGE);
            }
            txtAutor.setText("");
            break;
    }
    btnPotvrdi.setEnabled(false);
}

private void procitajPodatke() {
    if (poveziSeSaBazom()) {
        switch (dodajsta) {
            case 1:

                break;
            case 2:
                try {
                    sqlKomanda = Konekcija.createStatement();
                    upit = "select ida, autor from autor order by autor";
                    rs = null;
                    rs = sqlKomanda.executeQuery(upit);
                    if (rs != null) {
                        int i = 0;
                        while (rs.next()) {
                            podaci[i][0] = i + 1;
                            podaci[i][1] = rs.getInt("ida");
                            podaci[i][2] = rs.getString("autor");
                            i++;
                        }
                    }
                    rs.close();
                    sqlKomanda.close();
                } catch (SQLException esql) {
                    String poruka = "Gre\u0161ka: " + esql.toString() + "\n" + esql.getMessage();
                    JOptionPane.showMessageDialog(null, poruka, "Gre\u0161ka", JOptionPane.WARNING_MESSAGE);
                }
                vezaDB.prekiniVezuSaBazom(Konekcija);
                break;
        }
    }
}

}
View Answers

December 21, 2010 at 1:36 PM

Hello Friend, Try the following code:

import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*; 

public class UpdateJTable extends TimerTask {
private static JTable table = new JTable(); 
private static Vector columnNames = new Vector();
private static Vector data = new Vector();
private static JFrame f = new JFrame();
private static JScrollPane scrollPane = new JScrollPane();
public static void main(String[] args) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new UpdateJTable(), 0, 10000);
} public void run() {
remove();
table = draw(); 
scrollPane.getViewport().add(table, 0); 
f.getContentPane().add(scrollPane);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
f.pack(); 
} public static JTable draw() {
try { Class.forName("com.mysql.jdbc.Driver").newInstance(); 
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test", "root", "root");
String sql = "Select * from employee"; 
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)); }
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) { 
row.addElement(rs.getObject(i)); 
} data.addElement(row);
} rs.close();
stmt.close();
} 
catch (Exception e) {
System.out.println(e); 
e.printStackTrace(); 
 } 
table.setModel(new DefaultTableModel(data, columnNames));
TableColumn col;
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < table.getColumnCount(); i++) {
col = table.getColumnModel().getColumn(i);
col.setMaxWidth(col.getMaxWidth());
} return table;
}
public static void remove() {
columnNames.clear();
if (table.getRowCount() != 0) {
DefaultTableModel dm = (DefaultTableModel) table.getModel();
dm.getDataVector().removeAllElements(); 
 }
}
 }

Thanks









Related Tutorials/Questions & Answers:
how update JTable after adding a row into database
in JTable, and it's OK, but after adding a row into database table does't update. How update JTable after adding a row into database? package djile pak.java...how update JTable after adding a row into database  J have two
Java: Adding Row in JTable
Java: Adding Row in JTable   how about if we already have the JTAble created earlier. And i just found nothing to get its DefaultTableModel, thus, I can't call insertRow() method. Is there any work around for this? I found
Advertisements
jtable-adding a row dynamically
jtable-adding a row dynamically  hi..i am doing a project for pharmacy .. *pblm:* when i want to enter the details in jtable while running... to add one more row dynamically as a new row 4th if the details are large.but every
How to update,Delete database values from jtable cells ..
How to update,Delete database values from jtable cells ..  hello Sir... from database into jtable of a jpanel.. Now Sir, According to my need i have to update the cell values from there only means that whatever values i ma entering
how to make JTable to add delete and update sql database table
how to make JTable to add delete and update sql database table  Hello all I want to know how to make JTable to act actively to add delete and update database table. i am struck ed here from long time please help me
How to update,Delete database values from jtable cells ..
How to update,Delete database values from jtable cells ..  Hello Sir... from database to jtable .Now as per my requirement i need to update and delete the database records from the table cells by entering new values there only
How to update,Delete database values from jtable cells ..
How to update,Delete database values from jtable cells ..  Hello Sir, I am working on a project in which i have to fetch the values from database to jtable .Now as per my requirement i need to update and delete the database
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... ,update,delete database values from jtable only so i added three buttons add... of particular row is not getting added into the database whereas all other records
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... ,update,delete database values from jtable only so i added three buttons add,update... row is not getting added into the database whereas all other records are getting
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... ,update,delete database values from jtable only so i added three buttons add,update... row is not getting added into the database whereas all other records are getting
adding data to the database with the use of jtable - Java Beginners
adding data to the database with the use of jtable  how can i add data to the database with the use of jtable. and also can able to view the records in the database in the table.. tnx :G
adding data to the database with the use of jtable - Java Beginners
adding data to the database with the use of jtable  how can i add data to the database with the use of jtable. and also can able to view the records in the database in the table.. tnx :G
How to refresh a jTable On adding or deleting record ....
How to refresh a jTable On adding or deleting record ....   Hii... from same panel and i want jtable to be refreshed after every addition... that updates the jtable automatically after some interval of time. import
How to read and retrieve jtable row values into jtextfield on clicking at particular row ...
How to read and retrieve jtable row values into jtextfield on clicking at particular row ...  Hello Sir, I am developing a desktop application in which i have to display database records in jtable .now I want
jtable insert row swing
jtable insert row swing  How to insert and refresh row in JTable?   Inserting Rows in a JTable example
how to update specific row in on update key in the Navicat for mysql trigger
how to update specific row in on update key in the Navicat for mysql trigger   Blockquote insert into two(name, date) select name, curdate() from one on duplicate key update name=values(name
JTable duplicate values in row
JTable duplicate values in row  JTable duplicate values in row
how to update checkbox list in database
how to update checkbox list in database  Issues: i am using... to update one by one but it's not updating by using below code .it's not adding... in the database below logic is working fine by using insert command
How to delete and update from Jtable cell in swing app
How to delete and update from Jtable cell in swing app  Hii Sir, I am developing a swing app for adding,updating and deleting from jtable... is getting removed from the jtable but selected row is getting deleted from
update a JTable - Java Beginners
update a JTable   how to update a JTable with Mysql data through user... in an updatable JTable You would create the table as follows: conn... = new ResultSetTableModel(rs); table = new JTable(model
update a JTable - Java Beginners
update a JTable   i have tried your advice as how to update a JTable... main(String args[]) { JTable table; Connection con = null..."); ResultSetTableModel model = new ResultSetTableModel(rs); table = new JTable(model
Adding button to each row for the table and adding row to another table
Adding button to each row for the table and adding row to another table ... form database) and need to add that column data which we click in the specified row of the table
how to select the row value that was retrived from the database ?
how to select the row value that was retrived from the database ?  I am getting the data's from the table that was stored in database. Now in the page in which i am getting all the data from the database has an another select
how to select the row value that was retrived from the database ?
how to select the row value that was retrived from the database ?  I am getting the data's from the table that was stored in database. Now in the page in which i am getting all the data from the database has an another select
how to write a query for adding records in database
how to write a query for adding records in database  How write fire query in JSP for adding records in database
Adding JTable into existing Jframe.
Adding JTable into existing Jframe.  i need to add JTable into this code pls help me.. package Com; import Com.Details; import java.awt.Color...(100,60,1300,600); add(pane); //Action Listener for button //for adding new
Adding JTable into existing Jframe.
Adding JTable into existing Jframe.  i need to add JTable into this code pls help me.. package Com; import Com.Details; import java.awt.Color...(100,60,1300,600); add(pane); //Action Listener for button //for adding new
Adding JTable into existing Jframe.
Adding JTable into existing Jframe.  i need to add JTable into this code pls help me.. package Com; import Com.Details; import java.awt.Color...(100,60,1300,600); add(pane); //Action Listener for button //for adding new
JAVA DATABASE CONNECTION WITH JTABLE
JAVA DATABASE CONNECTION WITH JTABLE  HOw To Load Database Contents From Access Database to JTable without using Vector
how to return to main menu after adding all the info. - Java Beginners
how to return to main menu after adding all the info.  import java.util.Scanner; public class RegistrationSystem { public static void main(String[]args){ Scanner scan = new Scanner(System.in); int menu = 0
How to delete the row from the Database by using servlet
How to delete the row from the Database by using servlet  Dear Sir/Madam I am trying to delete the one user data in the Oracle SQL server database...: Delete row from database using servlet   In that link solution
update database
update database  hi.. i want to know how the valuesof database can... that can be done there then by pressing the update buutton the value can be updated to database
Update after delete
Update after delete  sir,i am working on online examination project in servlet.I am facing some problem that are -i have assign id column 1,2,3..... and i am deleting 3 record using id column of database mysql so now id
How to add a columns with a button set to a Jtable built with database result set
How to add a columns with a button set to a Jtable built with database result... balances of a particular person, after he logged with the correct user name..., amount of each transaction etc. now i have stucked in the point of adding
Enabling Row, Column and Cell Selections in a JTable
to describe how to enable the row, column and cell selections in a JTable... Enabling Row, Column and Cell Selections in a JTable... will see the enabling row, column and cell selections in a JTable. When you
add one row after another
add one row after another  how i add one row after another on click of add button $(document).ready(function() { var counter = 2; $("#addData").click(function() { if (counter > 10
Delete a row from database by id
Delete a row from database by id  I m creating a small application...) for "DELETE" AND "UPDATE". On clicking delete which is hyper link that particular row.... So anyone will tell me how to give hyper link to Delete and Update and delete
sqlite database delete row
sqlite database delete row  How to delete row from SQLite Database?    NSString *updateSQL = [NSString stringWithFormat: @"DELETE FROM aListDB WHERE id='%@'",details.ids
Removing a Row from a JTable
Removing a Row from a JTable       After inserting the data in a JTable, if you wish... the JTable. For removing the data of row from JTable, you will remove it from
Create After Update Trigger in SQL
Create After Update Trigger in SQL       After Trigger in SQL is fired before update... The Tutorial illustrate an example from 'Create After Update Trigger in SQL
update mysql database
update mysql database  update mysql database
Mysql Trigger after Update
Mysql Trigger after Update       Mysql Trigger after  Update fired automatically after we perform... understand an example from 'Mysql Trigger after Update'. To grasp 'Mysql
Show multiple identical rows into JTable from database
Show multiple identical rows into JTable from database In this tutorial, you will learn how to display the multiple rows from database to JTable. Here... rows from database on clicking search button to jtable. The given code accepts
Hibernate Update Query
Hibernate Update Query       In this tutorial we will show how to update a row with new information... write a java class to update a row to the database. Create a java class: Here
How to update record to database? I have trouble with the following code
How to update record to database? I have trouble with the following code  I have written the update statement but it still not work to update... mysql<em>selectdb($database_con, $connection); $emailAddress=$_POST
Connecting JTable to database - JDBC
interface in which i have used JTables.. Now my problem is I dont know how to how to store this JTable content in my database table.. This is a very important...Connecting JTable to database  Hi.. I am doing a project on Project
How to Restore The Lossed data in MYSQL database after the System is formatted
How to Restore The Lossed data in MYSQL database after the System is formatted  How to Restore The Lossed data in MYSQL database after the System is formatted
How to insert rows in jTable?
How to insert rows in jTable?  Hi, I need to take input from user using JTable. I want an empty row to appear after clicking a insert button... not figure out how to. I used DefaultTableModel but wasnt able to insert a row
How To Display both image and data into Swing JTable which is retrieved from ms access database
How To Display both image and data into Swing JTable which is retrieved from ms access database  So far this is my code how can i display both image and data from database.. while (rs.next()) { Vector row = new Vector(columns
Remove JTable row that read txt file records
Remove JTable row that read txt file records  Hi every one. i have a jtable that correctly read data frome file and show them in own. I want to add a "Delete" button that when select a row and clicked button, row must deleted

Ads