Update JTable

Hello,
I always thought that the table takes care for the view, whereas the tablemodel handles the data. But how come that an update with tblModel.setDataVector(...) destroys (resets to default) the preferred column width? Rather how can this be avoided?
import java.awt.*;
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 DefaultTableModel tblModel;
  public UpdateTable()
  { JFrame frame = new JFrame("UpdateTable");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    tblModel = new DefaultTableModel(data, headers)
    { // Make read-only
      public boolean isCellEditable(int x, int y)
      { return false;
    final JTable 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"};
//  Even if the next line is taken out the width changes.
    headers = headers_neu;
    tblModel.setDataVector((Object[][])data, (Object[])headers);
}Bye
J�rg

I agree, it doesn't make sense. Why does a setDataVector() method need a data vector and a column vector. Anyway I extended the DefaultTableModel and added a refreshDataVector() method that only needs a data vector.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class RefreshTableModel extends DefaultTableModel
    public RefreshTableModel()
        super();
    public RefreshTableModel(int numRows, int numColumns)
        super(numRows, numColumns);
    public RefreshTableModel(Object[][] data, Object[] columnNames)
        super(data, columnNames);
    public RefreshTableModel(Object[] columnNames, int numRows)
        super(columnNames, numRows);
    public RefreshTableModel(Vector columnNames, int numRows)
        super(columnNames, numRows);
    public RefreshTableModel(Vector data, Vector columnNames)
        super(data, columnNames);
    public void refreshDataVector(Vector data)
        fireTableRowsDeleted(0, getRowCount() - 1);
        dataVector = data;
        fireTableRowsInserted(0, getRowCount() - 1);
    public void refreshDataVector(Object[][] data)
        refreshDataVector( convertToVector(data) );
    public static void main(String[] args)
        Object[][] data = { {"four", "A"}, {"three", "B"}, {"two", "C"}, {"one", "D"} };
        String[] columnNames = {"Number", "Letter"};
        RefreshTableModel model = new RefreshTableModel(data, columnNames);
        JTable table = new JTable(model);
        table.getColumnModel().getColumn(0).setPreferredWidth(100);
        table.getColumnModel().getColumn(1).setPreferredWidth(200);
        JScrollPane scrollPane = new JScrollPane( table );
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add( scrollPane );
        frame.pack();
        frame.setVisible(true);
        try { Thread.sleep(3000); }
        catch (InterruptedException e) {}
        Object[][] refresh = { {"five", "E"}, {"six", "F"} };
        model.refreshDataVector( refresh );
}

Similar Messages

  • Update Jtable from access database

    as the title suggests help me guys... till now i have a database and some contents in it.. when the application starts the table is filled with contents of the database.. now whenever i add or remove a row in the databse i want to show it in the table... i have a Vector called dbData with the present contents of the database.. i want to update jtable with contents of dbData.... how to do it??

    the best things i can see to do is
    JTable table = new Jtable(.....); // this was ur table before;
    deleteRow(table); // you deleted the row
    // now you have a vector containing all the data for the rows;
    // but you need a vector containing the columns for the rows too
    //so now you do
    table = new JTable(dbData,columnnames);
    repaint();dbData must be a vector of vectors;
    dbData.elementAt(1) return a vector with all the data for row one
    so dbData.elementAt(1).elementAt(1) will be the data for row 1 column 1
    // dbData will be the data still remaining in the table
    or instead of the above you could use a nested for loop and set each element one at a time
    Object temp;
    int numberofRows = dbData.elementCount();
    int numberofColumns = db.elementAt(0).elementCount();
    for(int row = 0; row < numberofColumns;row++)
    for( int column = 0; column < numberofRows; column++)
      temp = dbData.elementAt(row).elementAt(column);
      table.setValueAt(temp,row,column);
    }

  • Clear and update JTable.

    Hi. this is a follow up from [Original Tread in "New To Java"|http://forums.sun.com/thread.jspa?messageID=10886612&#65533;]
    Hope you can help me here. For you who dont read the link. This application is build only to lay up here. So the Layout aint pretty. It compiles and run tho. What i want and cant get to work is to reload table when i push my JTabbedPane.
    Main Class
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        // clear and update JTable in class three
        public void clearThree() {
            Three t = new Three();
             t.clearVector();
        public JFrame frame() {
            JFrame frame = new JFrame();
            JTabbedPane tab = new JTabbedPane();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    clearThree();// this dont work
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }// class two
    package test;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    // class two&#347; only purpose is to  call clear() in class Three
    public class Two extends JPanel{
    public Two(){
    toolBar();
      public void clearThree () {
       Three t = new Three();
       t.clearVector();
      public void toolBar(){
      JToolBar bar = new JToolBar();
      JButton button = new JButton("clear");
      button.addActionListener(new ActionListener (){
          public void actionPerformed(ActionEvent e){
          clearThree(); // this dont work
    bar.add(button);
    add(bar);
    }// class three hold the table.
    package test;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    public class Three extends JPanel{ 
            DefaultTableModel model;
            JTable table;
            Vector v = new Vector();
            Vector a = new Vector();
            Vector<Vector> r = new Vector<Vector>();
        public Three() {
            jBar();
            jTable();
        public void clearVector(){
            v.removeAllElements();
            a.removeAllElements();
            r.removeAllElements();
            model.fireTableDataChanged();
        public void jBar() {
            JToolBar bar = new JToolBar();
            JButton button =  new JButton("clear");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    clearVector();// this does work
            bar.add(button);
            add(bar);
        public JScrollPane jTable(){
            v.addElement("ID");
            v.addElement("Name");
            a.addElement("01");
            a.addElement("Magnus");
            r.add(a);
            model = new DefaultTableModel(r,v);
            table = new JTable(model);
             JScrollPane pane = new JScrollPane(table);
             add(pane);
             return pane;
    }

    Thank you for your replay, I have taken all of your tips and modifed my original application. but the problem is still there. This has been a very messy thread. and it is becouse i thougth it were a table/model problem. But it&#347; not. In the code below I have a JTextField. When i push the JTabbedPanes i want the setText(); to kick in. this compile and run.
    // class One
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        public JFrame frame() {
            JTabbedPane tab = new JTabbedPane();
            final  Three t = new Three();
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                      t.setText(); // should call setText() in class Three.
            frame.add(panel);
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }class Two. Does nothing more then holding an empty tab
    package test;
    import javax.swing.*;
    public class Two extends JPanel{
    public Two(){
    emptyPane();
      public void emptyPane () {
      JLabel  label = new JLabel("Just an empty JTabbedPane");
      add(label);
      }class Three
    package test;
    import javax.swing.*;
    public class Three extends JPanel{ 
             JTextField text;
        public Three() {
            text();
        public void setText() {
            text.setText("Hello"); // this piece of code i want to insert in my JTextField
            validate();                // when i push the JTabbedPanes.
            repaint();
            updateUI();
        public JTextField text(){
             JToolBar bar = new JToolBar();
            text = new JTextField("",20);
            bar.add(text);
            add(bar);
            return text;
    }

  • Error in updating Jtable Database

    package desktopapplication1; import java.util.*; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.*; public class Datab extends DefaultTableModel { private Connection conn; private Statement st; private ResultSet rs; private ResultSetMetaData rsmd; private int rows; public Datab(String driver, String url, String query) throws SQLException, ClassNotFoundException { Class.forName(driver); conn = DriverManager.getConnection(url); st = conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE); if ( query.substring(0,3).equalsIgnoreCase("INS") ) { st.executeUpdate(query); } else if ( query.substring(0,3).equalsIgnoreCase("DEL") ) { st.executeUpdate(query); } else { rs = st.executeQuery(query); rsmd = rs.getMetaData(); rs.last(); rows = rs.getRow(); } fireTableStructureChanged(); } public String getColumnName(int column){ try{ return rsmd.getColumnName(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public int getColumnCount(){ try{ return rsmd.getColumnCount(); }catch(Exception e){ e.printStackTrace(); } return 0; } public int getRowCount(){ try{ return rows; }catch(Exception e){ e.printStackTrace(); } return 0; } public Object getValueAt(int row, int column){ try{ rs.absolute(row+1); return rs.getObject(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int column) { if (column < 0) { return false; } else { return true; } } public void setValueAt(Object value, int row, int column){ try{ int conf = JOptionPane.showConfirmDialog(null,"You wanna reaplace "+getValueAt(row,column)+" with "+value+"?", null, 2); if ( conf == 0 ) { rs.absolute(row+1); System.out.println("ROW = "+row+"CURSOR = "+(row+1)+""+rs.getString(1)+column); rs.updateString("Recipe","test"); //i tried to use a simple update cause the normal was not running but same error+ rs.updateRow(); }else { System.out.println("0"); } }catch(SQLException sqle){ System.err.println("Error setting value at row "+row+" column "+column+" with value "+value); sqle.printStackTrace(); } } }
    hi, when i click on my table to edit a value, it give me an error and sometimes fill the cell with a value like [B@341j0j
    Error setting value at row 1 column 0 with value soup2
    java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access]Error in row
    at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5271)
    at sun.jdbc.odbc.JdbcOdbcResultSet.updateRow(JdbcOdbcResultSet.java:4171)
    at desktopapplication1.Datab.setValueAt(Datab.java:104)
    at javax.swing.JTable.setValueAt(JTable.java:2719)
    at javax.swing.JTable.editingStopped(JTable.java:4721)
    at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)
    at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:350)
    at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:215)
    at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5475)
    at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:367)
    at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
    at javax.swing.JTextField.postActionEvent(JTextField.java:705)
    at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2886)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
    at java.awt.Component.processEvent(Component.java:6040)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
    at java.awt.Component.dispatchEventImpl(Component.java:4502)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    my db is like
    RecipeName intvalue1 intvalue2 intvalue3 stringvalue4
    soup 3 2 11 fish
    chocolate 3 2 44 dessert
    Edited by: kainard on Aug 1, 2010 2:31 PM
    Edited by: kainard on Aug 1, 2010 2:37 PM

    Can you explain why you declare
    private Connection conn;
    private Statement st;
    private ResultSet rs;
    private ResultSetMetaData rsmd;
    as private

  • Error while updating JTable

    WHAT I WANT TO DO:
    I display a list of items and their characteristics in a JTable (the content is in a DefaultTableModel). Each time a user buys items, I refresh the list for all the users currently connected to the server. The client buying the item is also prompted through a JOptionPane that his order has been processed.
    THE CODE:
    controller.handleOrder();
    JOptionPane.showMessageDialog(new JFrame(), message, "SUCCESSFUL ORDER", JOptionPane.INFORMATION_MESSAGE);Another thread calls the following function, which refreshes the list in the JTable:
    public void updateFlowers(){
         // method in Controller
         setChanged();
         notifyObservers();
        |
        V
    public void update(Observable arg0, Object arg1) {
         // method in Frame
         loadFlowers();
        |
        V
    private void loadFlowers(){
         // method in Frame
         flowerTableModel = controller.loadFlowers();
         flowerTable.setModel(flowerTableModel);
       |
       V
    public DefaultTableModel loadFlowers()  {
         // method in Controller
         Object table[][]=null;
         flowers=ClientOperations.getInstance().getFlowers();
         if (flowers!=null){
              table=new Object[flowers.size()][3];
              int i=0;
              for (Flower flower:flowers){
                   table[0]=flower.getSpecies();
                   table[i][1]=new Float(flower.getPrice());
                   table[i][2]=new Integer(flower.getInStock());
                   i++;
         DefaultTableModel flowersDTM=new DefaultTableModel(table,TABLE_HEADER);
         return flowersDTM;
    THE ERROR I GET:
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
         at java.util.Vector.elementAt(Unknown Source)
         at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paintGrid(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
         at javax.swing.plaf.ComponentUI.update(Unknown Source)
         at javax.swing.JComponent.paintComponent(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JComponent.paintToOffscreen(Unknown Source)
         at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
         at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
         at javax.swing.RepaintManager.paint(Unknown Source)
         at javax.swing.JComponent._paintImmediately(Unknown Source)
         at javax.swing.JComponent.paintImmediately(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.Dialog$1.run(Unknown Source)
         at java.awt.Dialog$3.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.awt.Dialog.show(Unknown Source)
         at javax.swing.JOptionPane.showOptionDialog(Unknown Source)
         at javax.swing.JOptionPane.showMessageDialog(Unknown Source)
         at javax.swing.JOptionPane.showMessageDialog(Unknown Source)
         at ui.OrderFrame.handleOrder(OrderFrame.java:185)
         at ui.OrderFrame.access$1(OrderFrame.java:181)
         at ui.OrderFrame$ButtonListener.actionPerformed(OrderFrame.java:218)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    I would very much appreciate it if you could explain why I get this error and how it can be solved.
    Thank you,
    Cristina                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Updating of Swing components must be done on the EDT. Wrap the code in SwingUtilities.invokeLater() or use a SwingWorker.
    Read the section from the Swing tutorial on Concurrency for more information.

  • How to auto update JTable during runtime

    Can anyone tell me how to dynamically update a JTable during execution, what i mean isin the I want the table to automatically add new rows as i enter new data.
    if I pass the object array reference of the TableModel to a method, then add more objects to the array and the revalidate the JTable will it work, or how do I do it ? Thanks

    Your table model should extend AbstractTableModel. And when (for example) it adds a row to whatever data structure is supporting the model, it should call fireTableRowsInserted... you can find out more about those methods in the API documentation. You don't need to revalidate or invalidate or validate the JTable, at least I don't have that in my code anywhere.

  • Update jtable cell via numeric keypad

    Hi,
    I have a problem, trying to figure out how to input numbers in a jtextfield in a jtable cell, from a group of jbuttons (rendered as a numeric keypad). I can get the cell to focus, but when I click on one of the jbuttons in the keypad, the cell loses focus and nothing is printed. I can update the cell by directly typing from the keyboard; that works fine. But I'm lost when trying to do it from the touch-screen keypad. Can anyone point me in the right direction. I assume I need to attach additional listeners somewhere.
    Thanks in-advance.
    Lee

    I can get the cell to focus, Then the code for you button would need to be something like:
    String text = (String)table.getValueAt(...);
    String updated = text + button.getText();
    table.setValueAt(updated, ...);

  • Update jtable from other window

    Hi !
    I have a jtable in window #1.
    When choose row I opened window #2.
    In window #2 I update sme details and want the
    table in window #1 to update.
    How can I do it ?
    Thank you for your help

    hi,
    1. In Win2 make a 'linked' object-variable to Win1, like:
    puplic javax.swing.JFrame Win2 extends JFrame{
       //* as type the class of your own win1! not a common window (javax.swing.JFrame)!
       private Win1 myWin1 = null;
       public Win2(Win1 parWin1){ window javax.swing.
          this.myWin1 = parWin1
    }2. Make a public getter-methode for your JTable in Win1
    puplic javax.swing.JFrame Win1 extends JFrame{
       private javax.swing.JTable myTable1 = null;
       public javax.swing.JTable getJTable(){
          return this.myTable1;
    }3. call your win2 with the new constructor
       Win2 myWin2 = new Win2(this);
       myWin2.show();4. Now you can work in Win2 with your JTable with
       ... this.myWin1.getTable1.....cu
    Oliver SCORP
    ps: normally you don't have to update your JTable - you have to do this with the (Data) Model of your JTable

  • Update JTable cells via setValueAt

    Hello all,
    I'm trying to implement a setValueAt method using an arrayList.....no success.What listeners should I have set up(For JTable or my table model)? I am new at this and I'm trying to update the JTable cells after a query from some db. Could anyone help?
    When trying to change the a value in the table I get these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at CachingResultSetTableModel.getValueAt(CachingResultSetTableModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

    I would think that everone who starts off with JTable will have a couple of concept problems. I am also going thru this learnig curve. It looks to me ( the blind leading the blind etc) like your basic table has strange data in it. The problem is occuring when the JTable is trying to setup the data from the table model.
    I don't think its anything to do with setValueAt.
    I kept going back to TableMap, TableSorter and JDBCAdaptor examples and copying the code from them to come right.> I debug by putting a System.out .... in all the methods until I get to where the code is giving trouble.
    Good luck [email protected]
    Hello all,
    >
    I'm trying to implement a setValueAt method using an
    arrayList.....no success.What listeners should I have
    set up(For JTable or my table model)? I am new at
    this and I'm trying to update the JTable cells after a
    query from some db. Could anyone help?
    When trying to change the a value in the table I get
    these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at
    CachingResultSetTableModel.getValueAt(CachingResultSetT
    bIleModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at
    javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt
    method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

  • Update JTable from String[][]

    Hello everyone, I have a JTable with a slightly customized DefaultTableModel shown below:
    DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames){
         private static final long serialVersionUID = 8655602888381735851L;
         @Override
             public boolean isCellEditable(int row, int column)
                         return false;
              };rowData is a String[][] of my data. When a user clicks a button, they add a row of data to the String[][]. I am wondering how I can update the JTable to reflect this change in the String[][]. Thanks!

    The problem with that is that I'm going to be performing various searches through the data, and those searches are performed on a TreeMap.
    rowData gets its data from the TreeMap, and is then displayedThe active verb does not describe the situation accurately: according to your code, rowdata is merely built from the TreeMap instance, and stuffed into a DefaultTableModel for display.
    When the user adds data, they add it to the TreeMap so that it can be searched.
    I can easily convert the data from the TreeMap to the String[][], but I don't know how to "redraw" the table with the new data.I assume the data is too big to repeat the process each time the user adds a row (build the new String[][], wrap it into a new DefaultTableModel instance and set the instance as the table's model).
    Another way is to duplicate the structure: when the user adds a row, add it into the searchable collection, and into the table model. But this costs twice the memory, and, again, I assume your data set is too large.
    A third, probably more elegant way is to build your own TableModel implementation: it could store a reference to the TreeMap instance, and an array converting the table's row index values to the tree's key value. That way the table model can be described in the active mode:
    "the JTable asks the model for cell values, and the model asks the tree for the corresponding data" :o)

  • Update JTable model col through header name in fast way

    old day, i update my JTable model through the way :
    tableModel.setValueAt(aValue, rowIndex, jTable1.getColumn("HeaderName").getModelIndex());now, i am adding a feature to my table, where the user can remove column.
    when user remove the column, is just the JTable GUI column being removed,. the underlining TableModel column is still there.
    my new feature will broke my above code.
    hence, i change my code to :
    for(columnIndex=0; columnIndex<columnCount; columnIndex++) {
         String name = tableModel.getColumnName(columnIndex)
         if(name.equals("HeaderName"))
              tableModel.setValueAt(aValue, rowIndex, columnIndex)
    }instead of looping through, is there any way i can retrieve the column model index in a fast way?
    a way i can think off, is inherit from DefaultTableModel, and add a map member, so that it can directly map the header name to col index.
    is there any better way?
    thanks

    i don't know why but the KeyListener does work fine with another application that i have also created Not a good solution. First of all the column still exists, so the user will tab from one column to your "hidden" column and wonder whats happening.
    The correct solution is to remove the TableColumn from the TableColumnModel. You can still access the data in the TableModel:
    table.getModel().getValueAt(...)
    No need to use the convertColumnIndexToModel.

  • How to force update jtable display

    I am trying to add some filtering funtionality to my swing application that uses a JTable. What I do is to filter the JTable's datamodel, and call repaint() on the jtable and JPanel, and do jframe.pack(); Sometimes it works, sometimes it doesn't. I check the jtable model, and it is being updated properly. I guess it is a GUI update problem. Is there a better way to force the whole app's GUI to be updated?
    //update tableModel
    //repaint() jtable;
    //repaint() jpanel;
    jf.pack();

    A couple questions
    1. Did you write your own table model? Not calling fireTableDataChanged() can cause problems in this case.
    2. Do you update the table from a thread? You might need to put the updates on the event thread (SwingUtilities.invokeNoow() or invokeLater()) or manually call fireTableDataChanged() (I'm not sure if this needs to happen on the event thread)

  • Updating JTable Contents

    I'm having trouble refreshing a JTable after changing it's 2D Object array data. Perhaps this is a stupid question, but any advice would be appreciated.
    Basically I've been building from the SimpleTableDemo.java file in the "How to Use Tables" tutorial. I set Object[][] data to a 2D Object array that is modified by other parts of my program.
    I added the public void tableChanged(TableModelEvent e) function to detect data changes, displaying a simple System.out, but it never seems to get called.
    Is there any way that the JTable can observe changes in the Object[][] data array and update it's self accordingly? I'm never sure if rows are being added or removed.
    I hope that made sense, and thank-you in advance to anyone who replies.
    -Arthur

    Couple of things...
    Whenever you change the contents of your TableModel you need to fire the appropriate event to get the JTable to update the viewed rows... in your case it sounds like you would have to call the "fireTableDataChanged()" method defined by AbstractTableModel so that your contents will be viewed.
    Also... it is rare that you really need to update the entire contents of your table model, most the time it is more efficient to just update the cell or row your need and call the appropriate "fire..." method to update
    Hope this helps
    Josh Castagno
    http://www.jdc-software.com

  • Problem updating JTable

    Hi,
    The code below only works if this.jTable1.setModel has not been called earlier during runtime.
    When it fails, the jTable simply does not update the displayed data.
    all.tableModel1.addColumn();
    this.jTable1.setModel(all.tableModel1);
    this.jTable1.repaint();What's the problem here? How do I perform a more "thorough" update?
    Regards,
    Pingen

    What's the problem here? How do I perform a more "thorough" update?I have no idea what you are trying to do based on the 3 lines of code you posted.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Updating JTable Column in real time

    Hello:
    I have a JTable which has listener listens for a specific event and updates the corresponding column accordingly in real time. This works fine. One small problems though, the user could actually see the redrawing of the JTable sometimes. Most of time, it went so fast, they don't see it, sometimes, user could see it. Why is it?

    try
    http://www.jgraph.com/pub/api/org/jgraph/event/GraphModelListener.html

Maybe you are looking for

  • Problems creating separate iTunes account from iPhone

    My wife and I have iPhones. I'm a MobileMe account user and my wife's email address is another email address within my MM account (I'm [email protected] and she is [email protected]). If we try to access iTunes with her existing email address it says the ID

  • I can't convert radio racording .aac file into .mp...

    Help me some one. When i record a radio file. It will be saved in .aac file. This .aac file aren't play in other device or computer. I want to convert into .mp3 file. Plz help me how to do this?

  • LDAP - Retrieve username & password

    Hi, I want to retrieve the username and password from LDAP server for the respective userId which is passed as an input. I am using javax.naming security package in java (1.6). Please help me how we can go about this? any examples or links are really

  • Step by Step Screen Saver using GPO

    Hi Guys, Can you please provide a step by step on how to deploy ScreenSaver using GPO to our Client users? Thanks in advance!!

  • Arabic description displayed in reverse format

    DEAR ALL In my smart output ARABIC DESCRIPTION displayed in reverse format that  means it displays in LTR format but  i need it in RTL format. If i reverse the description numbers goes to reverse.How i display it in RTL format. Can any body help on t