JTable update

Hi
I need to add to my jTable an jChecckbox in order to update row, but i do not kow how to add jChecckbox and how to create listner for each row ?, please find below my code :
package scratch;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.JLabel;
import java.awt.Rectangle;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.util.Vector;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.JComboBox;
import javax.swing.table.TableColumn;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import java.net.URL;
import javax.swing.JOptionPane;
import javax.swing.JButton;
public class Applet8 extends Applet {
boolean isStandalone = false;
Vector columnNames1 = new Vector();
Vector data1 = new Vector();
Connection connec;
String chaineconnexion = "jdbc:mysql://10.10.100.32:3306/FAX";
String login = "FAX";
String pass = "FAX";
public Connection getConnec() throws Throwable {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(chaineconnexion, login, pass);
BorderLayout borderLayout1 = new BorderLayout();
JCheckBox jCheckBox1 = new JCheckBox();
//Get a parameter value
public String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :
(getParameter(key) != null ? getParameter(key) : def);
//Construct the applet
public Applet8() {
//Initialize the applet
public void init() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
//Component initialization
private void jbInit() throws Exception {
// jLabel1.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
//jLabel1.setIcon(icon);
//jLabel1.setText("Tableau");
// Image icone = Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader ().getResource(new URL("icone.gif")));
//TableColumn cH = table3.getColumnModel().getColumn(6);
//cH.setCellEditor(DefaultCellEditor(comboBox));
//ImageIcon icon = new ImageIcon("fax.gif");
// JLabel label1 = new JLabel("",
// icon,
// JLabel.CENTER);
//label1.setFont(new java.awt.Font("Verdana", Font.BOLD, 50));
try {
connec = getConnec();
String sql = "SELECT Nom,DATE,RAIS_FAX AS Raison,FEED_BACK AS FeedBack ,USER,VAL as STATUS FROM FAX where subno =('')";
Statement stmt = connec.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Statement reqCDS = connec.createStatement();
// ResultSet Result = reqCDS.executeQuery(
// "SELECT * FROM task where n_tele ='70901661' ");
for (int i = 1; i <= 6; i++)
columnNames1.addElement( md.getColumnName(i) );
System.out.println( i );
while (rs.next())
Vector row = new Vector(columns);
for (int i = 1; i <= 6; i++)
row.addElement( rs.getObject(i) );
data1.addElement( row );
rs.close();
stmt.close();
catch(Exception e)
System.out.println( e );
} catch (Throwable ex) {
/** @todo Handle this exception */
JTable table3 = new JTable(data1, columnNames1);
table3.setCellSelectionEnabled(true);
// JButton total = new JButton("Total");
JScrollPane scrollane3 = new JScrollPane(table3 );
table3.setPreferredScrollableViewportSize(new Dimension(570, 400));
table3.addMouseListener(new Applet8_table3_mouseAdapter(this));
// jCheckBox1.setIcon(icon);
jCheckBox1.setText("Cheker");
this.add(jCheckBox1);
this.add(scrollane3);
scrollane3.getViewport().add(table3); // this.getImage(icone);//
//Get Applet information
public String getAppletInfo() {
return "Applet Information";
//Get parameter info
public String[][] getParameterInfo() {
return null;
public void table3_mouseClicked(MouseEvent e) {
//SystemException.outprint(res);
/// JOptionPane.showMessageDialog(null, "Erreur : "+(i));
//JOptionPane.showMessageDialog(this, "Vous devez saisir un feed back",
// "Erreur", JOptionPane.WARNING_MESSAGE);
class Applet8_table3_mouseAdapter extends MouseAdapter {
private Applet8 adaptee;
Applet8_table3_mouseAdapter(Applet8 adaptee) {
this.adaptee = adaptee;
public void mouseClicked(MouseEvent e) {
adaptee.table3_mouseClicked(e);
}

Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags when posting code to the code retains its original formatting and is readable.
Don't extend Applet, extend JApplet for a Swing application.

Similar Messages

  • Jtable Update problem .. Please help !!!!!!!!

    Hi ,
    I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
    But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
    Here is the code .... Please see it and tell me if it is possible :
    package newpackage;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Dimension;
    import java.text.*;
    import newpackage.ExcelExporter;
    import java.awt.Dimension;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Random.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableColumn;
    public class tab7le extends javax.swing.JFrame {
        Vector columnNames = new Vector();
        Vector data = new Vector();
        Connection con;
    Statement stat;
    ResultSet rs;
    int li_cols = 0;
    Vector allRows;
    Vector row;
    Vector newRow;
    Vector colNames;
    String dbColNames[];
    String pkValues[];
    String tableName;
    ResultSetMetaData myM;
    String pKeyCol;
    Vector deletedKeys;
    Vector newRows;
    boolean ibRowNew = false;
    boolean ibRowInserted = false;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        /** Creates new form tab7le */
        public tab7le() {
            populate();
            initComponents();
           public void updateDB(){
                     try{
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch (ClassNotFoundException e){
                System.out.println("Cannot Load Driver!");
          try{
             String url = "jdbc:odbc:FAMS";
             con = DriverManager.getConnection(url);
             stat = con.createStatement();
             rs = stat.executeQuery("Select * from SubAllot");
             deletedKeys = new Vector();
             newRows = new Vector();
             myM = rs.getMetaData();
             tableName = myM.getTableName(1);
             li_cols = myM.getColumnCount();
             dbColNames = new String[li_cols];
             for(int col = 0; col < li_cols; col ++){
                dbColNames[col] = myM.getColumnName(col + 1);
             allRows = new Vector();
             while(rs.next()){
                newRow = new Vector();
                for(int i = 1; i <= li_cols; i++){
                   newRow.addElement(rs.getObject(i));
                } // for
                allRows.addElement(newRow);
             } // while
          catch(SQLException e){
             System.out.println(e.getMessage());
    String updateLine[] = new String[dbColNames.length];
          try{
             DatabaseMetaData dbData = con.getMetaData();
             String catalog;
             // Get the name of all of the columns for this table
             String curCol;
             colNames = new Vector();
             ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
             while (rset1.next()) {
                curCol = rset1.getString(4);
                colNames.addElement(curCol);
             rset1.close();
             pKeyCol = colNames.firstElement().toString();
             // Go through the rows and perform INSERTS/UPDATES/DELETES
             int totalrows;
             totalrows = allRows.size();
             String dbValues[];
             Vector currentRow = new Vector();
             pkValues = new String[allRows.size()];
             // Get column names and values
             for(int i=0;i < totalrows;i++){
                currentRow = (Vector) allRows.elementAt(i);
                int numElements = currentRow.size();
                dbValues = new String[numElements];
                for(int x = 0; x < numElements; x++){
                   String classType = currentRow.elementAt(x).getClass().toString();
                   int pos = classType.indexOf("String");
                   if(pos > 0){ // we have a String
                      dbValues[x] = "'" + currentRow.elementAt(x) + "'";
                      updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                        pkValues[i] = currentRow.elementAt(x).toString() ;
                   pos = classType.indexOf("Integer");
                   if(pos > 0){ // we have an Integer
                      dbValues[x] = currentRow.elementAt(x).toString();
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString();
                      else{
                         updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                   pos = classType.indexOf("Boolean");
                   if(pos > 0){ // we have a Boolean
                      dbValues[x] = currentRow.elementAt(x).toString();
                      updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString() ;
                } // For Loop
                // If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
                int numNewRows = newRows.size();
                int insertRow = 0;
                boolean newRowFound;
                for (int z = 0;z < numNewRows;z++){
                   insertRow = ((Integer) newRows.get(z)).intValue();
                   if(insertRow == i+1){
                      StringBuffer InsertSQL = new StringBuffer();
                      InsertSQL.append("INSERT INTO " + tableName + " (");
                      for(int zz=0;zz<=dbColNames.length-1;zz++){
                         if (dbColNames[zz] != null){
                            InsertSQL.append(dbColNames[zz] + ",");
                      // Strip out last comma
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      InsertSQL.append(" VALUES(" + pkValues[i] + ",");
                      for(int c=1;c < dbValues.length;c++){
                         InsertSQL.append(dbValues[c] + ",");
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      System.out.println(InsertSQL.toString());
                      stat.executeUpdate(InsertSQL.toString());
                      ibRowInserted=true;
                } // End of INSERT Logic
                // If row has not been INSERTED perform an UPDATE
                if(ibRowInserted == false){
                   StringBuffer updateSQL = new StringBuffer();
                   updateSQL.append("UPDATE " + tableName + " SET ");
                   for(int z=0;z<=updateLine.length-1;z++){
                      if (updateLine[z] != null){
                         updateSQL.append(updateLine[z]);
                   // Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
                   updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
                   updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
                   System.out.println(updateSQL.toString());
                   stat.executeUpdate(updateSQL.toString());
                   } //for
             catch(Exception ex){
                System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
             // Delete records from the DB
             try{
                int numDeletes = deletedKeys.size();
                String deleteSQL;
                for(int i = 0; i < numDeletes;i++){
                   deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
                                                ((Integer) deletedKeys.get(i)).toString();
                System.out.println(deleteSQL);
                   stat.executeUpdate(deleteSQL);
                // Assume deletes where successful. Recreate Vector holding PK Keys
                deletedKeys = new Vector();
             catch(Exception ex){
                System.out.println(ex.getMessage());
        public void populate()
            try
                //  Connect to the Database
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
                System.out.println("ok1");
                //  Read data from a table
                String sql;
                 sql = "Select * from SubAllot";
                 System.out.println("ok1");
                Statement stmt = con.createStatement();
                System.out.println("ok1");
                ResultSet rs = stmt.executeQuery( sql );
                System.out.println("ok1");
                ResultSetMetaData md = rs.getMetaData();
                System.out.println("ok1");
                int columns = md.getColumnCount();
                for(int i = 0;i<columns;i++){
                    columnNames.addElement(md.getColumnName(i+1));
                    System.out.println("ok2");
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <columns+1; i++)
                        row.addElement( rs.getObject(i) );
                    data.addElement( row );
            catch(Exception e){
                e.printStackTrace();
                 public void dropmenu(JTable table,TableColumn subpref1) {
            //Set up the editor for the sport cells.
            JComboBox comboBox = new JComboBox();
          for (int i = 0;i<=20;i++)
           comboBox.addItem(i);
            subpref1.setCellEditor(new DefaultCellEditor(comboBox));
            //Set up tool tips for the sport cells.
            DefaultTableCellRenderer renderer =
                    new DefaultTableCellRenderer();
            renderer.setToolTipText("Click for combo box");
            subpref1.setCellRenderer(renderer);
                       abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    Object val = model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    data, columnNames
    jScrollPane1.setViewportView(table);
    //populate();
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    dropmenu(table, table.getColumnModel().getColumn(11));
    jButton1.setText("Update");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Ex");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(92, 92, 92)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(347, 347, 347)
    .addComponent(jButton1)
    .addGap(115, 115, 115)
    .addComponent(jButton2)))
    .addContainerGap(73, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(47, 47, 47)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(58, 58, 58)
    .addComponent(jButton1)
    .addContainerGap(83, Short.MAX_VALUE))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addGap(65, 65, 65))))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    updateDB(); // TODO add your handling code here:
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
    pathToDesktop = pathToDesktop + "//Final Allotment.xls";
    ExcelExporter exp = new ExcelExporter();
    exp.exportTable(table, new File(pathToDesktop));
    JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
    catch (IOException ex) {
    System.out.println(ex.getMessage());
    ex.printStackTrace();
    } // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new tab7le().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
    Please help !!!!!!!!
    Thanks in advance.....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
    Why post code with access to a database? We can't access the database.
    Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Strange JTable update problems

    I am having some strange issues with a JTable.
    I have a custom AbstractTableModel that displays various properties of a list of Objects. I am using a java.util.Vector to store this list.
    The user is given several JComboBox objects which contain filters for my table, when any of these filters are changed, a class that manages my Database is asked to return a Vector full of objects that match these filters.
    I then set my table data Vector equal to this returned list and invoke fireTableStructureChanged() from my table model. This part works fine, the strange thing is, if the user has a table element selected and then they change the filters, the table will not update, it actually goes blank, but oddly enough the scroll bar on the scroll pane stays the same length as the old table.
    When I invoke the exact same update method again (which just sets the Vector containing my data to a new value, and fires the event) the table will update this time.
    I have tried calling MyJTable.getSelectionModel().clearSelection() in the hope that it will fix my problem, but it does not seem to do anything.
    So is my problem some strange event or threading glitch, or an issue with JScrollPane mabye?
    Thanks in advance for any help

    Try using the DefaultTableModel to see if you have the same problem. If not then you know the problem is with your custom TableModel.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • JTable + update database

    hey all!!!
    i ve been searching the internet for a while but i don't seem to be able to find any solution to my problem. well, what i want to do is this...
    i have mysql db connected to my applets. i select from table and show the result in JTable on the interface. it all good and well but i am wondering whether it possible to update the table and then, let's say press button, and also update the databse or not?? what i mean is whether i have to press the button get values in the corresponding row, load the values into JTextFields and then press another button and update the database or whether i can just change the JTable and then press only one button and everything that's in the JTable will get, magically, updated in the database without having to use the middle JTextField step??
    v.v.

    are you a soldier??No, but I served in the Navy for 5 years.
    >
    thanks that's exactelly what i needed.... will give
    it a read
    v.v.You're welcome; happy reading.

  • JTable update, column headers

    I am trying to write my own tablemodel which does not change the specified
    column widths when updating. So far everthing works fine, only the column
    headers are not repainted. Does anybody know what is missing?
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class UpdateTable
    { static String headers[]= {"Baum", "Blatt", "Frucht","H�usigkeit"};;
      static String data[][]= {
         {"Eiche", "gez�hnt","Eichel","ein"},
         {"Buche", "glatt", "Buchecker","ein"},
         {"Tanne", "Nadel", "Zapfen","ein"},
         {"Pappel", "wechselst�ndig","Kapsel","zwei"},
      static MyTableModel tblModel;
      static JTable table;
      public UpdateTable()
      { JFrame frame = new JFrame("UpdateTable");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        tblModel = new MyTableModel(data, headers)
        { // Make read-only
          public boolean isCellEditable(int x, int y)
          { return false;
        table = new JTable(tblModel);
        table.getColumnModel().getColumn(1).setPreferredWidth(200);
        table.getColumnModel().getColumn(3).setPreferredWidth(20);
          // Set selection to first row
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        selectionModel.addListSelectionListener (new ListSelectionListener()
        { public void valueChanged(javax.swing.event.ListSelectionEvent e)
            if (e.getValueIsAdjusting()) return;
                System.out.println(table.getSelectedRow());
          // Add to screen so scrollable
        JScrollPane scrollPane = new JScrollPane (table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(500, 100);
        frame.setVisible(true);
      public static void main(String args[])
      { new UpdateTable();
        try
        { Thread.sleep(3000);
        catch (InterruptedException e)
        { System.out.println ("Fehler: "+ e.toString());
        String headers_neu[] = {"Arbre", "Feuille", "Fruit", "Maisonette"};
        headers = headers_neu;
        data[0][0]= "Eberesche";
        tblModel.setDataVector(data, headers);
    //    table.revalidate(); // is of no use.
        table.repaint();
    // The table model
    class MyTableModel extends AbstractTableModel
      private int cols, rows;
      private String[] columnNames;
      private String[][] data;
      public MyTableModel(int cols, int rows)
      { this.cols = cols;
        this.rows = rows;
      public MyTableModel(String[][] data, String[] columnNames)
      { setDataVector(data, columnNames);
      public String getColumnName(int col)
      { return columnNames[col].toString();
      public int getColumnCount()
      { return cols;
      public int getRowCount()
      { return rows;
      public Object getValueAt(int row, int col)
      { return data[row][col];
      public void setDataVector(String[][] data, String[] columnNames)
      { this.cols = data[0].length;
        this.rows = data.length;
        this.data= data;
        this.columnNames= columnNames;
    //    Firing the event will change column widths as usual.
    //    fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););
    }

    // fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););
    You have to fire a table changed event.
    The table neverasks the model if things have changed. The model always notifys the table of changes.
    No event fired no table repaint.
    Instead of fireTableChanged(...) you have the option of fireTableDataChanged() (if only the data has changed, not the nomber of columns or the type of columns) and fireTableStructureChanged() (if there have been columns changed).
    If fireTableStructureChanged happens (and HEADER_ROW event is the same thing), the table removes the columns and creates new onew. That's why column sizes are lost.
    If you really want the table not to manage columns, you have to do it yourself:
    Implement your own TableColumnModel and pass it to the table constructor. When adding/removing columns you can ask what was the size of the previous columns where and set the new columns to that size.
    Call setAutoCreateColumnsFromModel(false) in your table constructor so that the table will not remove/create new columns itself when a tableStructureChanged event happens.

  • Problem with a JTable Update

    I have a JDialog with a JTable and JScrollPane.
    JTable uses TableModel.java
    Now, when I am tryint to scroll to the right, the name of the columns, that was out of window won't redraw and the text is merged. The rows are ok. Only the titles.
    How to get the column names updated?
    Here is the code:
    TableTest.java (JDialog)
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class TableTest extends JDialog {
         private JPanel jContentPane = null;
         private JScrollPane jScrollPane = null;
         private JTable jTable = null;
         private TableModel tableModel = null; 
          * This is the default constructor
         public TableTest() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.add(getJScrollPane(), java.awt.BorderLayout.NORTH);
              return jContentPane;
          * This method initializes jScrollPane     
          * @return javax.swing.JScrollPane     
         private JScrollPane getJScrollPane() {
              if (jScrollPane == null) {
                   jScrollPane = new JScrollPane();
                   jScrollPane.setPreferredSize(new java.awt.Dimension(453,100));
                   jScrollPane.setViewportView(getJTable());
              return jScrollPane;
          * This method initializes jTable     
          * @return javax.swing.JTable     
         private JTable getJTable() {
              if (jTable == null) {
                   jTable = new JTable();
                   jTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
                   jTable.setModel(getTableModel());
                   jTable.setPreferredSize(new java.awt.Dimension(500,80));
              return jTable;
          * This method initializes tableModel     
          * @return TableModel     
         private TableModel getTableModel() {
              if (tableModel == null) {
                   tableModel = new TableModel();
              return tableModel;
    TableModel.javaimport javax.swing.table.AbstractTableModel;
    public class TableModel extends AbstractTableModel {
         private String[] columnNames = {"First Name",
                   "Last Name",
                   "Sport",
                   "# of Years",
         "Vegetarian"};
         private Object[][] data = {
                   {"Mary", "Campione",
                        "Snowboarding", new Integer(5), new Boolean(false)},
                        {"Alison", "Huml",
                             "Rowing", new Integer(3), new Boolean(true)},
                             {"Kathy", "Walrath",
                                  "Knitting", new Integer(2), new Boolean(false)},
                                  {"Sharon", "Zakhour",
                                       "Speed reading", new Integer(20), new Boolean(true)},
                                       {"Philip", "Milne",
                                            "Pool", new Integer(10), new Boolean(false)}
         public final Object[] longValues = {"Sharon", "Campione",
                   "None of the above",
                   new Integer(20), Boolean.TRUE};
         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];
         * JTable uses this method to determine the default renderer/
         * editor for each cell. If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
         public void setValueAt(Object value, int row, int col) {
              data[row][col] = value;
              fireTableCellUpdated(row, col);

    Heres your code (reworked a little to show what i mean)
    does this solve your issue?
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class TableTest extends javax.swing.JFrame {
         private JPanel jContentPane = null;
         private JScrollPane jScrollPane = null;
         private JTable jTable = null;
         private TableModel tableModel = null; 
          * This is the default constructor
         public TableTest() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.add(getJScrollPane(), java.awt.BorderLayout.NORTH);
              return jContentPane;
          * This method initializes jScrollPane     
          * @return javax.swing.JScrollPane     
         private JScrollPane getJScrollPane() {
              if (jScrollPane == null) {
                   jScrollPane = new JScrollPane();
                   jScrollPane.setPreferredSize(new java.awt.Dimension(453,100));
                   jScrollPane.setViewportView(getJTable());
              return jScrollPane;
          * This method initializes jTable     
          * @return javax.swing.JTable     
         private JTable getJTable() {
              if (jTable == null) {
                   jTable = new JTable();
                   jTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
                   jTable.setModel(getTableModel());
                   //jTable.setPreferredSize(new java.awt.Dimension(500,80)); //this line is causing your error, but i dont know why
              return jTable;
          * This method initializes tableModel     
          * @return TableModel     
         private TableModel getTableModel() {
              if (tableModel == null) {
                   tableModel = new TableModel();
              return tableModel;
            public static void main (String[] main)
                new TableTest().setVisible(true);
    class TableModel extends AbstractTableModel {
         private String[] columnNames = {"First Name",
                   "Last Name",
                   "Sport",
                   "# of Years",
         "Vegetarian"};
         private Object[][] data = {
                   {"Mary", "Campione",
                        "Snowboarding", new Integer(5), new Boolean(false)},
                        {"Alison", "Huml",
                             "Rowing", new Integer(3), new Boolean(true)},
                             {"Kathy", "Walrath",
                                  "Knitting", new Integer(2), new Boolean(false)},
                                  {"Sharon", "Zakhour",
                                       "Speed reading", new Integer(20), new Boolean(true)},
                                       {"Philip", "Milne",
                                            "Pool", new Integer(10), new Boolean(false)}
         public final Object[] longValues = {"Sharon", "Campione",
                   "None of the above",
                   new Integer(20), Boolean.TRUE};
         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];
          * JTable uses this method to determine the default renderer/
          * editor for each cell.  If we didn't implement this method,
          * then the last column would contain text ("true"/"false"),
          * rather than a check box.
         public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
         public void setValueAt(Object value, int row, int col) {
              data[row][col] = value;
              fireTableCellUpdated(row, col);
    }

  • JTable Updating

    I am updating a JTable. I pass a String into the method which updates the table. I have 5 columns in this table.It is putting the value of this String into every column. I need to put specific values into specific columns. My class extends AbstractTableModel, I have tried a few scenarios but none of them have worked.
    Thanks

    post some code... clearly, you're doing something wrong

  • JTable - Updating TableModel does not increase num rows until column resize

    Hi all,
    I'm developing an application which includes a JTable with a TableModel implementation.
    The table model consists of 2 columns - Property and Value.
    * A table model for server properties
    * Created on 09-May-2005
    package com.jc.editor.model;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import javax.swing.table.AbstractTableModel;
    * @author crossja
    public class PropertyTableModel extends AbstractTableModel {
      private String[] columnNames = {"Property", "Value"};
      private String[][] data;
      public PropertyTableModel(LinkedHashMap p_propertiesMap)
        setProperties(p_propertiesMap);
      public void setProperties(LinkedHashMap p_propertiesMap){
        data = new String[p_propertiesMap.size()][2];
        // Insert data from hashmap into data array
        Iterator props_iterator = p_propertiesMap.keySet().iterator();
        String curr_property;
        for(int i=0 ; props_iterator.hasNext(); i++){
          curr_property = (String)props_iterator.next();
          data[0] = curr_property;
    data[i][1] = (String)p_propertiesMap.get(curr_property);
    * Get the number of columns in the table model
    public int getColumnCount() {
    return columnNames.length;
    } // getColumnCount()
    * Get the column name at the given index
    public String getColumnName(int p_index){
    return columnNames[p_index];
    }// getColumnName(int)
    * Get the number of rows in the table model
    public int getRowCount() {
    return data.length;
    } // getRowCount()
    public Object getValueAt(int rowIndex, int columnIndex) {
    return data[rowIndex][columnIndex];
    } // getValueAt()
    } // end PropertyTableModel
    When another method updates the table model, it calls the setProperties method. However, this doesn't update the JTable fully until I resize a column in the table. Here's the strange behaviour:
    If the table initially has 2 rows, and the new table model has 5 rows, then the two visible rows in the table JTable will be updated to the new values, but the three new rows do not appear. However, if I resize a column, they suddenly appear, and with the correct values.
    I've tried calling repaint on the JTable, and JPanel, but that doesn't solve the problem.
    The JTable is displayed within a JScrollPane.
    Regards,
    Jim

    change the following two lines in your program...
          data[0] = curr_property;
    data[i][1] = (String)p_propertiesMap.get(curr_property);
    // double-check the row & col indices are correct
    setValueAt(curr_property, i, 0);
    setValueAt(curr_(String)p_propertiesMap.get(curr_property), i, 1);

  • Need help on Implementing timer based JTable update events

    greetings,
    i am writing a trap receiver that placed the entries in a jtable, and i am having a problem where the entires can arrive so fast they swamp the event thread. the solution i believe is to write a custom model that calls the table update events on timer based intervals. i have made an attempt at this, but cannot get it to work. has anyone done this, or possibly tell me where i have gon off the tracks?
    thanks in advance,
    here is my class:
    import javax.swing.event.TableModelEvent;
    import javax.swing.table.DefaultTableModel;
    public class TimerUpdateTableModel extends DefaultTableModel implements Runnable{
         Thread runner;
           int rowCtr = 0;
         public TimerUpdateTableModel(int initialDelay) {
             Thread runner = new Thread(this);
             runner.start();
         public void fireTableDataChanged(){
              //super.fireTableDataChanged();
         public void fireTableStructureChanged(){
              //super.fireTableStructureChanged();
         public void fireTableRowsInserted2(int firstRow,
                int lastRow){
              //super.fireTableRowsInserted(firstRow, lastRow);
         public void fireTableRowsInserted(int firstRow,
                int lastRow){
              //super.fireTableRowsInserted(firstRow, lastRow);
         public void fireTableRowsUpdated(int firstRow,
                int lastRow){
              //super.fireTableRowsUpdated(firstRow, lastRow);
         public void fireTableRowsDeleted(int firstRow,
                int lastRow){
              //super.fireTableRowsDeleted(firstRow, lastRow);
         public void fireTableCellUpdated(int row,
                int column){
              //super.fireTableCellUpdated(row, column);
         public void fireTableChanged(TableModelEvent e){
              //super.fireTableChanged(e);
         public void run() {
              while (true) {
                   try{
                        rowCtr = TimerUpdateTableModel.this.getRowCount();
                        System.out.println(rowCtr + "    " + (TimerUpdateTableModel.this.getRowCount() - 1));
                        //super.fireTableRowsInserted(0, TimerUpdateTableModel.this.getRowCount() - 1);
                        //super.fireTableDataChanged();
                        int nRowCount = getRowCount();
                        super.fireTableChanged (new TableModelEvent (TimerUpdateTableModel.this, 0,
                            nRowCount - 1,
                            TableModelEvent.ALL_COLUMNS,
                            TableModelEvent.UPDATE));
                   }catch(Exception e){
                        e.printStackTrace();
                   try {
                        Thread.sleep(5000);
                   } catch (InterruptedException ie) {
                   }catch(Exception e){
                        e.printStackTrace();
                   System.out.println("done");
    }

    i am having a problem where the entires can arrive so fast they swamp the event thread
    super.fireTableChanged Well, if you are using the above code every time you receive an update, then I suspect you would be having problems. The fireTableChange() event is an expensive method. It means you need to recreate the TableColumnModel and repaint the entire table every time.
    You should simply be using method like model.addRow(...), model.setValueAt(...) to make updates to the table.

  • Efficient JTable updates

    RE: Java 1.5 Update 16
    All,
    I'm sure I'm not covering new ground here, but my web searches are not resulting in any useful information. I'm trying to figure out how to efficiently update a JTable when the underlying data model changes. I'm aware of the AbstractTableModel and API such as fireTableCellUpdated. However, the problem I've observed is that the JTable code seems to be redrawing a rect around all the cells that have changed during a particular EventQueue loop. So, let's say just two cells have changed 0:0 and X:Y where X = numRows and Y = numCols. Even though only two cells have been updated (i.e. I have called fireTableCellUpdated twice in succession on 0:0 and X:Y), in my testing, the entire table is redrawn, because the two cells in question are the upper left cell and the lower right cell in the table. The JTable redrawing code seems to draw one big rect around both cells and ends up updated everything in between. If I break up the calls to fireTableCellUpdated to separate passes through the EventQueue, then just the corners are updated. However, in the case of my data model and rapid firing of updates, I cannot break things up this way. Does anyone know if there's any better way to approach this? Any advice would be much appreciated.

    I'm attaching code that demonstrates this issue. Note that the code purposely does not make use of the DefaultTableModel's setValueAt API. Use of this method would fire table cell updates. I'm updating the underlying data, and then manually firing the updates so that the issue manifests itself quite starkly when the app is run. In the default form, the entire table is updated. If you follow the comments and modify the code, you'll see the app run with only the upper left and lower right hand corner cells updating. Note also that I do not necessarily think this is a bug in JTable. You can imagine a somewhat inverted scenario where many interior cells are updated but not all. If JTable made a bunch of separate calls to draw small individual rects, that might end up being much less efficient than simply redrawing the whole table.
    public class TableUpdateTest extends JFrame {
        public static void main(String[] args) {
            new TableUpdateTest();
        private static final Random RANDOM = new Random();
        public static int randomIntInRange(int low, int high) {
            if (low == high) {
                return low;
            if (low>=high) {
                throw new IllegalArgumentException("Cannot generate randomIntInRange because low " + low + " is not less than high " + high + ".");
            int random;
            synchronized (RANDOM) {
                random = (Math.abs(RANDOM.nextInt()) % ((high+1) - low)) + low;
            return random;
        TableUpdateTest() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final Vector<Vector<String>> data = new Vector<Vector<String>>();
            Vector<String> datum = new Vector<String>();
            datum.add("Suzanne");
            datum.add("Smith");
            datum.add("Suzie");
            data.add(datum);
            datum = new Vector<String>();
            datum.add("Joseph");
            datum.add("Bank");
            datum.add("Joey");
            data.add(datum);
            datum = new Vector<String>();
            datum.add("Ezra");
            datum.add("Pound");
            datum.add("Ezzie");
            data.add(datum);
            datum = new Vector<String>();
            datum.add("Gordon");
            datum.add("Lightfoot");
            datum.add("Gordo");
            data.add(datum);
            datum = new Vector<String>();
            datum.add("Thomas");
            datum.add("Pickering");
            datum.add("Tom");
            data.add(datum);
            datum = new Vector<String>();
            datum.add("Jerry");
            datum.add("Mathers");
            datum.add("Beaver");
            data.add(datum);
            Vector<String> columnNames = new Vector<String>();
            columnNames.add("First Name");
            columnNames.add("Last Name");
            columnNames.add("Nick Name");
            final DefaultTableModel dataModel = new DefaultTableModel(
                    data,
                    columnNames
            new Timer(250, new ActionListener() {
                private boolean toggle;
                public void actionPerformed(ActionEvent e) {
                    // Switch everyone's names around by manipulating
                    // the underlying data structures and NOT using
                    // the DefaultTableModel API which would fire an
                    // update for every cell in the table.
                    for (int i = 0, size = data.size(); i < size; i++) {
                        Vector<String> datum1 = data.get(i);
                        int otherIndex = randomIntInRange(0, size-1);
                        Vector<String> datum2 = data.get(otherIndex);
                        String lastName = datum1.get(0), firstName = datum1.get(1), nickName = datum1.get(2);
                        datum1.set(0, datum2.get(0));
                        datum1.set(1, datum2.get(1));
                        datum1.set(2, datum2.get(2));
                        datum2.set(0, firstName);
                        datum2.set(1, lastName);
                        datum2.set(2, nickName);
                    // Now that everyone is jumbled, fire updates to the
                    // upper left and lower right hand corners only.
                    // These two lines together cause the entire
                    // table to be redrawn.
                    dataModel.fireTableCellUpdated(0,0);
                    dataModel.fireTableCellUpdated(data.size(),2);
                    // Uncomment the code below and comment out the two lines
                    // above, and watch just the corner cells update.
                    /*if (toggle) {
                        dataModel.fireTableCellUpdated(0,0);
                    } else {
                        dataModel.fireTableCellUpdated(data.size()-1,2);
                    toggle = !toggle;*/
            }).start();
            JPanel panel = new JPanel(new BorderLayout());
            JTable table = new JTable();
            table.setModel(dataModel);
            JScrollPane scrollPane = new JScrollPane(table);
            panel.add(scrollPane);
            setContentPane(panel);
            setSize(350, 200);
            setLocation(300, 300);
            setVisible(true);
    }

  • Please Help me in JTable Updating   - URGENT

    Hai all
    am corrently working on a project which am using swing of 1.4
    here in one screen when user enteres data in JTable and clicks submit button i must read the whole Table model of the table and i will insert it to DB.
    in this am gettting problem.
    that is
    when user enters data into jtable and user directly clicks submit i can take all the data iin the table but only on tablce colum value i cant take which is the user currencly entering or modifying the filed.
    if after entering data i need to click any other cell or i need to just click tab to come out of the cell then only i cant take the data from that cell when inserting .
    pls anybody help me how to come out of this problem.
    thanking you
    Rajesh

    Hi
    before you save the changes you have to call stopCellEditing method.

  • JTable Updates From a Separate Thread?

    Using the code below, the "Thread Row" cell never shows up in the applet (the addRow method doesn't seem to work from a separate thread). Any suggestions would be appreciated.
    Andrew
    public class TestClass extends Applet {
    DefaultTableModel m_tableModel;
    public void init() {
    m_tableModel = new DefaultTableModel(0, 3);
    m_tableModel.addRow(new Object[]{"start"});
    JTable jtable = new JTable(m_tableModel);
    this.add(jtable);
    Thread blah = new Thread(new temp());
    blah.start();
    private class temp implements Runnable {
    public void run() {
    m_statusTableModel.setValueAt("Thread Test", 0, 1);
    m_statusTableModel.fireTableDataChanged();
    m_statusTableModel.addRow(new Object[]{"Thread Row"});
    m_statusTableModel.fireTableDataChanged();
    }

    That was a typo. I renamed it and it still doesn't work. The "Thread Row" cell still does not show up. I am using IE5.5 with the following as my html page that references the applet. Can you please post the HTML you used to view your applet, as well as the browser you are using?
    <HTML>
    <HEAD>
    <TITLE></TITLE>
    </HEAD>
    <BODY>
    <OBJECT classid="clsid:CAFEEFAC-0013-0001-0000-ABCDEFFEDCBA"
    id="upapplet" name="upapplet" WIDTH = 510 HEIGHT = 414
    codebase="http://java.sun.com/products/plugin/1.3.1/jinstall-131-win32.cab#Version=1,3,1,0">
    <PARAM NAME = CODE VALUE = "JTableApplet.class" >
    <PARAM NAME="type" VALUE="application/x-java-applet;jpi-version=1.3.1">
    <COMMENT>
    <EMBED
    type="application/x-java-applet;jpi-version=1.3.1"
    CODE = JTableApplet.class
    WIDTH = 400
    HEIGHT = 400
    scriptable=false
    pluginspage="http://java.sun.com/products/plugin/index.html#download">
    <NOEMBED>
    alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
    Your browser is completely ignoring the <APPLET> tag!
    </NOEMBED>
    </EMBED>
    </COMMENT>
    </OBJECT>
    </BODY>
    </HTML>

  • JTable update itself.

    Hi
    I have a Jtable that is based on a vector of vectors for the data model. Anyway, is there a way for Jtable to listen to see if the data in the vector changed from an external source, like the internet? I can change the vector but the values in the JTable remain the same. I have to use setvalue at to get things going, I wan Jtable to check the vecotrs itself. As well adjust the number rows and columns according to the vecotrs.

    check out http://www.globalleafs.com 's download section. There are many programmes out there in java.

  • Want jtable  to be refreshed...on change of the textfield change..

    The code is below and question follows the code :
    import java.sql.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.event.*;
    public class sample extends JFrame
         JTable tableFindsymbol;
         JFrame FindSymbolFrame;
         JTextField symbolText = new JTextField(35);
        private String getsymbolTextfieldtext;
        private int columns;
         Vector columnNames = new Vector();
        Vector data = new Vector();
        private String query;
         public sample()
                   FindSymbolFrame = new JFrame("sample");
                  FindSymbolFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                  Container myPane = FindSymbolFrame.getContentPane();
                  myPane.setLayout(new GridBagLayout());
                  GridBagConstraints c = new GridBagConstraints();
                  setMyConstraints(c,0,0,GridBagConstraints.CENTER);myPane.add(getFieldPanel(),c);
                  setMyConstraints(c,0,1,GridBagConstraints.CENTER);myPane.add(getTable(),c);
                  FindSymbolFrame.pack();
                  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                  Dimension frameSize = FindSymbolFrame.getSize();
                  FindSymbolFrame.setLocation(new Point((screenSize.width - frameSize.width) / 2 , (screenSize.height - frameSize.width) / 2));
                  FindSymbolFrame.setVisible(true);
         public JPanel getFieldPanel()
              JPanel p = new JPanel(new GridBagLayout());
              p.setBorder(BorderFactory.createTitledBorder("Enter Details"));
              GridBagConstraints c = new GridBagConstraints();
              setMyConstraints(c,0,0,GridBagConstraints.CENTER);p.add(symbolText,c);
              symbolText.addKeyListener(listener);
              return p;
         KeyListener listener = new KeyListener()
                    public void keyPressed(KeyEvent e) {}
                    public void keyReleased(KeyEvent e)
                              getsymbolTextfieldtext = symbolText.getText();
                              getTable();
                   public void keyTyped(KeyEvent e){}
         public JPanel getTable()
              try{
                        query =  "SELECT SYMBOL, CO_NAME FROM CO_DB_WITH_NAME where CO_NAME LIKE '"+ getsymbolTextfieldtext +"'";
                        JOptionPane.showMessageDialog(null,query);
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:sdb","scott","tiger");
                        final Statement st = con.createStatement();
                        ResultSet rs = st.executeQuery(query);
                        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();
              }catch(Exception e)
                               System.out.println( e );
                        JPanel tablePane = new JPanel(new GridBagLayout());
                        DefaultTableModel model = new DefaultTableModel(data,columnNames);
                        tableFindsymbol = new JTable(model);
                        tablePane.add(tableFindsymbol);
                         JScrollPane scrollPane = new JScrollPane(tableFindsymbol);     
                         getContentPane().add(scrollPane);
                        tablePane.add(getContentPane());
                        tableFindsymbol.setRowSelectionAllowed(true);
                        tableFindsymbol.setColumnSelectionAllowed(false);
                        tablePane.setVisible(true);
                      return tablePane;
         private  void setMyConstraints(GridBagConstraints c, int gridx, int gridy, int anchor)
              c.gridx = gridx;
              c.gridy = gridy;
              c.anchor = anchor;
         public static void main(String[] args)
              sample fsymf=new sample();
    }what i want to do is: make the jtable get updated as soon the text in the text field changes..
    how do i call the jtable panel so it updates the table or any jtable update method
    Thanks for reply in advance..

    Quit multi-posting questions.
    You where already given the answer to this question in your last posting:
    [http://forum.java.sun.com/thread.jspa?threadID=5270240]
    Also, in the future don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Simple question concerning "persisting JTable data?"

    Hi fellow bloggers,
    I couldn't find this info in the Sun JTable tutorial. The tutorial explains how to update a cell in a JTable, but it doesn't suggest a method for persisting the "row" once it has been modified. Furthermore, the JTable tutorial states the following in the leading summary:
    "JTable does not contain or cache data; it is simply a view of your data."
    Does this mean that the data structure which is used to populate the JTable must be updated on a row by row basis, as well as updating the JTable itself? Isn't there some way to select a row on the JTable, update the row of data, and then port the data in a row of cells to a completely separate data structure?
    Thanks.

    If you want your data cached or persistent, you do that in the TableModel. DefaultTableModel will already be persistent. What they mean in that quote is that whenever the JTable needs a value for cell it queries the TableModel for the value.
    I'm not sure why you want/need/care to port the data in a completely separate data structure, but sure... you can do that. Create a class and feed the data into it however you please, that'll be that.

Maybe you are looking for