JTable in Swing

hi,
Good Morning,
I am using NetBeans and MS-Access to develop a simple project.
I am using JTable to store all the records from my MS-Access Database.
When I run the project all the records are stored in JTable .No Problem.
But when I insert new records ,they are not added to the JTable.But when I run the project again the recently inserted records are stored in the JTable.
Need I refresh my table?
Is any method to refresh?
or chance of any mistake in my coding?

hi,
Thank you so much for your reply.
My coding is below.But I didnot use the method of model.addRow().I am using
jTable m_table = new JTable();
m_table.addColumn(column);
column is created by me and i am using DefaultTableCellRenderer .Because I am new to java I donot know how to implement your reply in my coding.So please help me to solve.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class ss extends JFrame
protected JTable m_table;
protected StockTableData m_data;
protected JLabel m_title;
public ss()
super("Stocks Table");
setSize(600, 340);
m_data = new StockTableData();
getContentPane().add(m_title, BorderLayout.NORTH);
m_table = new JTable();
m_table.setAutoCreateColumnsFromModel(false);
m_table.setModel(m_data);
for (int k = 0; k < StockTableData.m_columns.length;k++) {
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setHorizontalAlignment(StockTableData.m_columns[k].m_alignment);
TableColumn column = new TableColumn(k, StockTableData.m_columns[k].m_width,renderer,null);
m_table.addColumn(column);
JTableHeader header = m_table.getTableHeader();
header.setUpdateTableInRealTime(false);
JScrollPane ps = new JScrollPane();
ps.getViewport().add(m_table);
getContentPane().add(ps,BorderLayout.CENTER);
WindowListener wndCloser = new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
addWindowListener(wndCloser);
setVisible(true);
public static void main(String argv[]) {
new StocksTable();
class StockData
public String m_code;
public String m_name;
public String m_ic;
public String m_address;
public String m_phone;
public StockData(String symbol,String name, String last, String open, String change)
m_code = symbol;
m_name = name;
m_ic = last;
m_address = open;
m_phone = change;
class ColumnData
public String m_title;
public int m_width;
public int m_alignment;
public ColumnData(
String title, int width,
int alignment)
m_title = title;
m_width = width;
m_alignment = alignment;
class StockTableData extends AbstractTableModel
static final public
ColumnData m_columns[] = {
new ColumnData(
"SCODE", 100, JLabel.LEFT ),
new ColumnData(
"NAME", 150, JLabel.LEFT ),
new ColumnData(
"IC", 100, JLabel.RIGHT ),
new ColumnData(
"ADDRESS", 100, JLabel.RIGHT ),
new ColumnData(
"PHONE", 100, JLabel.RIGHT ),
protected Vector m_vector;
public StockTableData() {
m_vector = new Vector();
setDefaultData();
public void setDefaultData() {
try {
m_vector.removeAllElements();
Connection con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:SERTS";
String user = "root";
String pw = "";
con = DriverManager.getConnection(url,user,pw);
Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String tofirst="SELECT * from [Student-File]";
ResultSet results;
results = s.executeQuery(tofirst);
boolean hasData = false;
while (results.next())
if (!hasData)
m_vector.removeAllElements();
hasData = true;
String scode = results.getString(1);
String sname = results.getString(2);
String address = results.getString(3);
String ic = results.getString(4);
String phone = results.getString(5);
m_vector.addElement(new StockData(scode,sname,address,ic,phone));
results.close();
s.close();
con.close();
catch (ClassNotFoundException e)
System.out.println (e.getMessage());
System.exit(0);
catch (SQLException e)
System.out.println (e.getMessage());
System.exit(0);
public int getRowCount() {
return m_vector==null ? 0 : m_vector.size();
public int getColumnCount() {
return m_columns.length;
public String getColumnName(int column) {
return m_columns[column].m_title;
public boolean isCellEditable(int
nRow, int nCol) {
return false;
public Object getValueAt(int
nRow, int nCol) {
if (nRow < 0 || nRow
>= getRowCount())
return "";
StockData row =
(StockData)m_vector.elementAt(nRow);
switch (nCol) {
case 0: return row.m_code;
case 1: return row.m_name;
case 2: return row.m_ic;
case 3: return row.m_address;
case 4: return row.m_phone;
return "";
public String getTitle() {
return "Stock Quotes";
Thank you so much.

Similar Messages

  • Delete multiple rows in a JTable ADF Swing.

    hi guys,
    Would anyone know tell me how do I delete multiple rows in a JTable ADF Swing?
    JDeveloper.

    Hi,
    I would configure the table for multi row selection. Then get the selected row index, access the iterator in the PageDef file (through the panelBinding reference you have in ADF Swing) and then iterate over the selected row indexes, make an index to become the current row and call remove() on it
    Frank

  • Change Row Backgroud color in Jtable : ADF Swings

    Hi ,
    I have developed a ADF Swings Details Form . On Details FORM LOAD if Check Box is TRUE( means selected) i have to change the back ground color of the JTable row and also i have make that row as READ ONLY mode .
    Need help.
    Regards
    Bhanu Prakash

    ok i found how to do it
    i directly inserted this in the renderer code:
    if (row == table.getSelectedRow() && column == table.getSelectedColumn())
    cell.setBackground(etc);
    (curiously it does not work with "if (isSelected)")
    thanks :)

  • How to make SMOOTH scrolling with Jtable in Swing automatically ?

    Hi All,
    I'm coding for a price board program, with all records I designed a table for them. So now I want to scroll automatically for all records on that table for customers viewing them. The problem that I can make it scroll smoothly ! Currently I use this block code :
    Thread scollTable;
    int scrollCount = 38;
    public void scrollTable(final int records) {
    if (scollTable == null) {
    scollTable = new Thread() {
    @Override
    public void run() {
    try {
    while (true) {
    if (scrollCount == 38) {
    jTable1.setRowSelectionInterval(scrollCount, scrollCount);
    scrollRowToVisible(scrollCount, jTable1);
    Thread.sleep(4000);
    jTable1.setRowSelectionInterval(scrollCount, scrollCount);
    scrollRowToVisible(scrollCount, jTable1);
    Thread.sleep(1000);
    scrollCount++;
    if (scrollCount == records) {
    scrollCount = 0;
    Thread.sleep(4000);
    jTable1.setRowSelectionInterval(scrollCount, scrollCount);
    scrollRowToVisible(scrollCount, jTable1);
    scrollCount = 38;
    continue;
    } catch(Exception ex) {
    if (!scollTable.isAlive()) {
    //scollTable.setPriority(7);
    scollTable.start();
    public void scrollRowToVisible(int row, JTable table) {
    Rectangle cellRect = table.getCellRect(row, 0, true);
    Rectangle visibleRect = table.getVisibleRect();
    cellRect.x = visibleRect.x;
    cellRect.width = visibleRect.width;
    table.scrollRectToVisible(cellRect);
    The problem I think the progam can not run smoothly with scroll :
    scrollRowToVisible(scrollCount, jTable1);
    Thread.sleep(1000);
    scrollCount++;
    Any helps,
    Thanks.
    Edited by: onlysang2004 on Aug 4, 2009 2:22 AM

    Could you please tell me more detail ? I studied about Swing recently ! I found a link for that javax.swing.Timer : http://forums.sun.com/thread.jspa?threadID=5366085&messageID=10603235#10603235 but how can I use ? In my price board screem doesn't have ActionListener object or button to listen to submit. Can I create an ActionListener object ? Please help me more, how to run smooth scrolling automatically !
    public class ViewElectricHaSTC extends JFrame {
    Thread scollTable;
    public ViewElectricHaSTC(Options options) throws Exception {
    scrollTable(options.getRecord());
    int scrollCount = 38;
    public void scrollTable(final int records) {
    if (scollTable == null) {
    scollTable = new Thread() {
    @Override
    public void run() {
    try {
    while (true) {
    if (scrollCount == 38) {
    //jTable1 created with initComponents method
    jTable1.setRowSelectionInterval(scrollCount, scrollCount);
    scrollRowToVisible(scrollCount, jTable1);
    Thread.sleep(4000);
    jTable1.setRowSelectionInterval(scrollCount, scrollCount);
    scrollRowToVisible(scrollCount, jTable1);
    Thread.sleep(1000);
    scrollCount++;
    if (scrollCount == records) {
    scrollCount = 0;
    Thread.sleep(4000);
    jTable1.setRowSelectionInterval(scrollCount, scrollCount);
    scrollRowToVisible(scrollCount, jTable1);
    scrollCount = 38;
    continue;
    } catch(Exception ex) {
    if (!scollTable.isAlive()) {
    //scollTable.setPriority(7);
    scollTable.start();
    public void scrollRowToVisible(int row, JTable table) {
    Rectangle cellRect = table.getCellRect(row, 0, true);
    Rectangle visibleRect = table.getVisibleRect();
    cellRect.x = visibleRect.x;
    cellRect.width = visibleRect.width;
    table.scrollRectToVisible(cellRect);
    Edited by: onlysang2004 on Aug 4, 2009 7:23 PM

  • Working with Combo boxes in JTable in swings

    Hello everyone,
    I am working on swing components. We are designing a swing based platform for our company. I have a case where i have to use comboboxes in a jtable. I have seen a lot of topics on this but i have an issue with that. We have to implement a type ahead feature in these comboboxes where if we type any key the items in the table which start with that alphabet or sybol are selected. We can see this by default in regular comboboxes but i have been unable to implement this in the jtable. I have tried various ways like adding listeners etc. and none of them are working. This is my code for the cell renderers for these comboboxes
    public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public MyComboBoxRenderer(Vector items) {
    super(items);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    super.setBackground(table.getSelectionBackground());
    } else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    setSelectedItem(value);
    return this;
    public class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(Vector items) {
    super(new JComboBox(items));
    Can anyone who has faced a similar issue help me regarding this.
    Thanks in advance
    Edited by: bharat20 on Nov 14, 2007 6:58 AM

    Hi,
    Have you tried the Swing forums at java.sun.com? This is the Java Studio Enterprise IDE Forum, so you probably won't get much response here.
    http://forum.java.sun.com/category.jspa?categoryID=7
    Also, what IDE tools are you using?
    R

  • Problem in cell selection in JTable Java Swing

    hii
    I am using JTable that shows data from database. I have developed one functionality. I change one cell value and then select multiple cell. If I press F12 function key then it copies first selected value and past it to another selected cells. it is working properly but when I press F12 it sets the last selected cell in editable mode. I want that all cell which has been pasted should be selected (with default blue colour not in editing mode). I am using ListSelectionListener for JTable Cell Selection and KeyListener for F12 functionality.
    Please give some solution
    I can not override editCellAt Method because i have already extended JFrame. and i tried to do this with Jtable.getSelectedColumn and getSelectedRow it is displaying the same value, by this how can I get the particular area of selection means Row nd Column Selected.
    How would I know the current selection when user selects more than one cell???
    Thanks
    Edited by: 850979 on 11-Apr-2011 02:13
    Edited by: 850979 on 11-Apr-2011 03:59

    camickr wrote:
    Presumably, JTable installs an action for the F12 key that results in starting editing the last selected cell.
    There are no bindings for F12. See the [url http://www.camick.com/java/blog.html?name=key-bindings]Key Bindings listing. (...)
    Right.
    Of course it doesn't make sense that a F? key should invoke the editorI thought he meant F2 ("edit" on Windows), so that sounded natural.
    All KeyEvents are passed to the editor for the cell and the editor is psuedo invoked. That is, the caret is not placed on the text field used as the editor, but the character typed is added to the editor. You can then either use tab/enter to save the text or use the escape key to cancel the editing.Thanks for the explanation. I had never noticed (I kept on double-clicking my JTable cells when I wanted to edit them! :o)
    Of course it doesn't make sense that a F? key should invoke the editor, but this is a by product of all KeyEvents being forwarded so you don't have to have special Key Bindings for every character.You're right - as always.
    They (Sun) could have filtered out some of the keys such as those, though, because as noted by the OP the current behavior is unintuitive.
    To better control when the cell is editable based on the KeyEvent you can override the table with code like <snipped>
    As you suggested using a Key Binding will prevent this behaviour as well (but only for that key).Right again, but in this specific case that is acceptable (the developer wants to attach a specific behavior to a specific key only).
    OP here is an SSCCE of that second approach:
    public class TestKeyBindingsOnJTable {
        public static void main(String... args) {
            final DefaultTableModel dtm = new DefaultTableModel(new String[] {"A", "B"}, 0);
            dtm.addRow(new String[]{"A1", "B1"});
            dtm.addRow(new String[]{"A2", "B2"});
            dtm.addRow(new String[]{"A3", "B3"});
            JTable table = new JTable(dtm);
            table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), "clear");
            table.getActionMap().put("clear", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    dtm.removeRow(0);
            JOptionPane.showMessageDialog(null, table);
    }Edited by: jduprez on Apr 8, 2011 9:36 PM

  • Connection of jtable of swing  with sql server database in netbeans 6.5

    i want to know how to retrieve values from sql server database in a jtable in netbeans 6.5 and i also want edit and delete buttons in in row so that by clicking on it a particuler record can be updated and deleted.please help me it is urgent

    Just in case anyone has the same issue:
    I found that latest JDK v 12 as some problems:
    http://www.nabble.com/Problem-Adding-Server-in-Server-List-td21810860.html
    I installed JDK update 11 and re-installed netbeans. Now everything is working fine.
    ~ Tushar

  • Help regarding JTable in Java Swing

    hi,
    i m confused regarding JTable in Swing. i hav added a JTextField in a cell of a JTable. i hav attached a kay listener with that textfield . But when i m selecting that cell ,where i hav added that textfield with a single click and typeing any key i m not getting that keyevent. But when i m selecting the same with a doulbe click and typing any thing i m getting that event .
    can any one tell me why the discrepency taking place. that textfield is
    there in that cell .then how it does make any difference with a single and double click.
    regards

    i hav added a JTextField in a cell of a JTableYou don't add a text field to a cell in a table. You add a text String to the TableModel. When the user double clicks on the cell an 'editor' is invoked and the text is copied to the editor (which by default is a JTextField). So the KeyStrokes go to the editor text field.
    When you just single click on a cell the table still has focus, not the editor, to the KeyStroke character is passed directly to the text field without the text field actually getting focus.

  • Using the swing worker to populate the data in to jtablle

    Hello, i am developing my 1st application in java swings , i have developed it but when i run a module which fetchces the data from the mysql and display it in jtable my swing gui got blank for some initial time, i was thinking for some progress bar type thing but when i came acroos google i found that i can use swing worker to load my GUI on time and in the back ground i can do the task of fetching the data from the data base and populating the Jtable, but i had done a lot of try but not succeded to implement the swing worker . Please help me to implement the swing worker :( . i am using the abstractTableModal to populating the jtable it is working fine but swing worker is not there .
    Scenerio is like this i have base frame on which i got 1 or more btton one of those button is Clients when i click on it a Jdialog box appears with the jtable . Pleae tell me how to implement the swing worker class between this. Pleaseeeeeeeeeeeeeeeeeeeeee :( I am help less now .

    Fahim i want to display some photograph in to a swing application after fetching these photo graph from the database table , i dont know what swing component will be better for it and i m designing this in netbeans , so please assist me with that , how to go now and please note that it is dynamic so component should be like that :(. i m trying to create a photo album where i upload the multiple photograph first then i would like to show them each photograph will a text box when some one write some text in that text box and press enter i would like to save that text with that photo graph , I AM DONE WITH THE PHOTO UPLOADING TASK BUT DONT KNOW HOW TO DO THE REST LIKE DISPLAYING THE PHOTOGRAPH WITH THAT TEXT BOX .
    Edited by: kamal.java on Apr 27, 2012 8:59 AM

  • Problem: Is this how i update/refresh a JTable?

    Newbie in JTable and Swing here.
    I have created panel class which will load data from the database when first time come into this panel
    JScrollPane sp1 = new JScrollPane();
    PlayerTableModel pModel = new PlayerTableModel();
    JTable table1 = new JTable(pModel);
    upon a combobox change, i will refresh my table with new data...
    void cb_position_actionPerformed(ActionEvent e) {
    PlayerTableModel pModel = new PlayerTableModel(str_item);
    pModel.fireTableDataChanged();
    table1.repaint() ;
    but the above codes does not seems to refresh and update my table..
    help..
    Thanks...

    I have a piece of example code from a book that I've been working with lately. In this case when a certain combo box changes the table data is refreshed.
    Here is how it's done:
    if (scrollPane != null)
    getContentPane().remove(scrollPane);
    try
    String tableName= (String)tableNames.getSelectedItem();
    if (rs != null) rs.close();
    String query = "SELECT * FROM " + tableName;
    rs = stmt.executeQuery(query);
    if (SCROLLABLE)
    model = new ScrollingtbSchedule1Model(rs);
    else
    model = new CachingtbSchedule1Model(rs);
    JTable table = new JTable(model);
    scrollPane = new JScrollPane(table);
    getContentPane().add(scrollPane, "Center");
    pack();
    doLayout();
    catch(SQLException e)
    System.out.println("Error " + e);
    Notice that the pane is removed and then added again with the new data to force a "refresh".

  • How to bind a JTable in runtime.

    Hello Guys,
    Anyone know tell me how to bind a JTable adf Swing at Runtime?
    In other words, I want to create the bindings when the application to be running.
    Thanks in advanced.

    Try the static createAttributeListBinding() methods in JUTableBinding.
    Sascha

  • JTable printing problem

    Hi , I have a problem add printing routine for printing to this code.
    Sombody help me.
    I no post all code but my prube no functioned.
    thanks you
    code :
    package com.froses.tablemodels;
    * SimpleDBTable.java
    * A demonstration of using ODBC to read data from an Access database
    * and display the values in a JTable.
    * This file requires that the new.mdb file exists and has been mapped
    * using ODBC to a datastore named 'newdb' with blank username and password.
    * Gordon Branson January 2004
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class SimpleDBTable extends JPanel {
    private boolean DEBUG = true;
    private int rows = 10, cols = 5;
    private String url = "jdbc:odbc:Sego";
    private Connection con;
    private Statement stmt;
    private JButton btnRead, btnDelete, btnWrite, btnClose;
              /* Setup the table column names */
    private String[] columnNames = {"Medico",
    "Descripci�n",
    "Obra social",
    "Items",
    "Codigo"};
              /* declare an Object array large enough to hold the database table */
    private Object[][] data = new Object[rows][cols];
    private JTable table;
    public SimpleDBTable() {
    super(new BorderLayout());
    /* Load ODBC diver */
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
              /* create the JTable */
    table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 300));
    /* Now read from the database */
    populateTable();
    if (DEBUG) {
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    printDebugData();
    //Create the Title Label.
    JLabel title = new JLabel("Database Access in Java");
    title.setFont(new java.awt.Font("Arial", 1, 24));
    title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    //Add the label to this panel.
    add("North",title);
    //Create the scroll pane and add the JTable to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this panel.
    add("Center",scrollPane);
    // Create a button panel with a default layout
    JPanel buttons = new JPanel();
    // Create the buttons
    btnRead = new JButton("Read");
    btnClose = new JButton("Close");
    btnWrite = new JButton("Write");
    btnDelete = new JButton("Delete");
    // Add action listeners
    btnRead.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    populateTable();
    btnDelete.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    deleteTable();
    btnWrite.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    writeTable();
    btnClose.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    System.exit(0);
    // Add the buttons to the button panel
    buttons.add(btnRead);
    buttons.add(btnWrite);
    buttons.add(btnDelete);
    buttons.add(btnClose);
    // Add the buttons panel to main panel
    add("South",buttons);
    private void populateTable(){
         /* Define the SQL Query to get all data from the database table */
    String query = "SELECT * FROM Datos";
    /* First clear the JTable */
    clearTable();
    /* get a handle for the JTable */
    javax.swing.table.TableModel model = table.getModel();
    int r = 0;
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
    stmt = con.createStatement();
    /* run the Query getting the results into rs */
                   ResultSet rs = stmt.executeQuery(query);
                   while ((rs.next()) && (r<rows)) {
                        /* for each row get the fields
                        note the use of Object - necessary
                        to put the values into the JTable */
                   Object nm = rs.getObject("Medico_solic");
                   Object sup = rs.getObject("Descip_Item");
                   Object pri = rs.getObject("Obra_Social");
                   Object sal = rs.getObject("M�dico_opera");
                   Object tot = rs.getObject("Codigo_estudio");
                   model.setValueAt(nm, r, 0);
                   model.setValueAt(sup, r, 1);
                   model.setValueAt(pri, r, 2);
                   model.setValueAt(sal, r, 3);
                   model.setValueAt(tot, r, 4);
                   r++;
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    private void deleteTable(){
         emptyTable();
         clearTable();
    private void emptyTable(){
         /* Define the SQL Query to get all data from the database table */
    String query = "DELETE * FROM COFFEES";
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
    stmt = con.createStatement();
    /* run the Query */
                   stmt.executeUpdate(query);
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    /* private void writeTable(){
         /* First clear the table */
    /*      emptyTable();
         PreparedStatement insertRow;// = con.prepareStatement(
         String insertString = "INSERT INTO COFFEES " +
                                  "VALUES (?, ?, ?, ?, ?)";
    int numRows = table.getRowCount();
    javax.swing.table.TableModel model = table.getModel();
    Integer sup, sal, tot;
    Double pri;
    Object o;
    if(DEBUG) System.out.println("\nDoing Write...");
    try {
    /* connect to the database */
    /* con = DriverManager.getConnection(url, "", "");
    insertRow = con.prepareStatement(insertString);
         for (int r=0; r < numRows; r++) {
              if (model.getValueAt(r, 0) != null){
                   insertRow.setString(1, (String) model.getValueAt(r, 0));
                   //o = model.getValueAt(r, 1);
                   if(DEBUG) System.out.println(model.getValueAt(r, 1).toString());
                   sup = new Integer((String) model.getValueAt(r, 1));
                   insertRow.setInt(2, sup.intValue());
                   pri = new Double((String) model.getValueAt(r, 2));
                   insertRow.setDouble(3, pri.doubleValue());
                   sal = new Integer((String) model.getValueAt(r, 3));
                   insertRow.setInt(4, sal.intValue());
                   tot = new Integer((String) model.getValueAt(r, 4));
                   insertRow.setInt(5, tot.intValue());
                   insertRow.executeUpdate();
                   System.out.println("Writing Row " + r);
    insertRow.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    clearTable();
    private void writeTable(){
         /* First clear the table */
         emptyTable();
         Statement insertRow;// = con.prepareStatement(
         String baseString = "INSERT INTO Datos " +
                                  "VALUES ('";
         String insertString;
    int numRows = table.getRowCount();
    javax.swing.table.TableModel model = table.getModel();
    Integer sup, sal, tot;
    Double pri;
    Object o;
    if(DEBUG) System.out.println("\nDoing Write...");
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
         for (int r=0; r < numRows; r++) {
              if (model.getValueAt(r, 0) != null){
                   insertString = baseString + model.getValueAt(r, 0)+"',";
                   insertString = insertString + model.getValueAt(r, 1)+",";
                   insertString = insertString + model.getValueAt(r, 2)+",";
                   insertString = insertString + model.getValueAt(r, 3)+",";
                   insertString = insertString + model.getValueAt(r, 4)+");";
                   if(DEBUG) System.out.println(insertString);
              insertRow = con.createStatement();
                   insertRow.executeUpdate(insertString);
                   System.out.println("Writing Row " + r);
    insertRow.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    clearTable();
    private void clearTable(){
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    for (int i=0; i < numRows; i++) {
    for (int j=0; j < numCols; j++) {
    model.setValueAt(null, i, j);
    private void printDebugData() {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("SimpleDBTable");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    SimpleDBTable newContentPane = new SimpleDBTable();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    http://forum.java.sun.com/thread.jspa?threadID=626207

  • JFrame And jTables

    Hi
    I can connect a database to a table in a normal class just fine. But doing it in jFrame is mind boggling. I have put a jPanel on the frame. I have put my table in a scrollpanel. But i have no idea how to connect it to the database. Appreciate your help with this coz ive been trying to figure out for the better part of the last 3 weeks.

    But i have no idea how to connect it to the databaseThere is no way to connect a JTable directly to a database.
    I can connect a database to a table in a normal class just fineEvery class is a "normal" class. So just do exactly as you have been doing. The only difference is that instead of doing a System.out.println(...) to display the results of the database query you need to built a DefaultTableModel which you then add the to the JTable.
    Swing related questions should be posted in the Swing forum. If you search the Swing forum you will find my "tablefromdatabase" example.

  • Sum Columns in a jTable?

    (Wasn't completely sure where to post this... but jTable is Swing, right?)
    I have a jTable displaying a database table containing integers corresponding to seats booked. I want to sum these integers in a final column.
    However, the table also contains Primary and Foreign key columns which are also integers. I don't want to sum these, obviously.
    Like this:
    PKey FKey1 FKey2    Col1  Col2  Col3  Col4  Total
    1    2     3        1     0     2     1     4
    2    3     3        1     1     2     2     6
    3    6     8        1     3     1     1     6However, I really haven't been doing this very long, and have no idea where/how to sum these values. Do I write some kind of renderer? Can I do some kind of "int Total = Col1+Col2... etc;"? Or do I sum the values on a lower level and then display the result in the table? In other words: "Help! I'm lost!"

    Well you would probably calculate the total as you first populate the TableModel.
    Then if you data changes dynamciallly you would use a TableModelListener to recalculate the total. Here is a simple example:
    [http://forums.sun.com/thread.jspa?forumID=57&threadID=566133]

  • JTable Help To add a column

    Hi friends
    I hava a problem:-
    IN SHORT I WANT TO ADD A COLUMN TO THE JTABLE. Please read to understand the problem...
    I made a class called clsViewUsers which implements AbstractTableModel. This class fetches data and this data is put in the JTable with the constructor JTable(javax.swing.table.TableModel dm).
    Now I want to add a column to the table without disturbing the TableModel.
    I tried JTable.addColumn(javax.swing.table.TableColumn aColumn).
    I made TableColumn UserStatusColumn = new TableColumn();
    This TableColumn class has a function called setCellRenderer(TableCellRenderer aRenderer). This function takes a TableCellRenderer.
    I made a class which implements this TableCellRenderer. This class compiles well but when this returns the java.awt.Component class to setCellRenderer(TableCellRenderer aRenderer)(Function above). Then it gives compile error as setCellRenderer(javax.swing.table.TableCellRenderer) in javax.swing.table.TableColumn cannot be applied to (java.awt.Component).
    IN SHORT I WANT TO ADD A COLUMN TO THE JTABLE.
    Please help
    Vishwajeet Wadhwa

    You can use a vector called columNames to store the column names and create a method like
    public void addColumn(String columnName) {
    columnNames.add(columnName);
    you can make your model implement an interface that has a method for adding columns like
    public interface ChangeableColumn{
    public void addColumn(String columnName);
    and have some other object like a panel with a button hold a reference to the TableModel which implements the interface
    somePanel.addChangeableColumnListener(ChangeableColumListener tablemodel){
    this.columnListener = tablemodel;
    and the panel can have a method called addColumn(String columnName){}
    that will called the method in the interface which will be implemented in the model
    something like that maybe

Maybe you are looking for

  • My dashboard taking long time to load in ipad compared to Desktop. Experts need suggestion to tune my dashboard.

    Hi Experts,          I have developed dashboard with BEX query as a source(9 queries used in dashboard). This dashboard opens in 40 secs in BI launchpad but if I open same dashboard through SAP BI app it almost taking 3-4 min. Is there any ways to im

  • Disp+work process starts than dies in SAP R/3 4.7 Ent. server

    I stopped SAP R/3 4.7 ent server for backup, when i restart the Microsoft management console the disp+work process turns yellow to grey. Can any one help me to solve this problem??? O/s :Windows2000 server database :SAPDB 7.3 Here iam attaching the l

  • G. Total of Doc. Total in A/R Invoice

    Dear Experts, I want a report on the basis of sales employee in which we need the sum of doc. total or row total of the document in which sales employee is same. For Example : There are 10 Documents of A/R Invoice of the same sales employee & Custome

  • Saving a completed form

    I've created a PDF form, but when my customer completes the form, he is unable to save it. There is a message that he cannot save the form with data in it; he can only print it. He's running Reader 8. Can you tell me if there's a setting that I need

  • Windows XP - Elements 1.0 and MPG files

    When I add MPG file to the Media window in Elements and then double click on them they play perfectly including the audio. When I drag them to the Timeline the video plays but there is no audio. AVI files work perfectly. Possible operator error. Any