JTable Model

Hi,
I have a JTable haing four columns and i am showing that on one screen.
Now i need the same JTable to be shown on different screen, but with only
3 columns. Can anyone please advice how can i do it.
I appreciate your help.

Using the same model would work fine if the data you were displaying was identical in both tables. However, you have stated that you want the data to be different in each table. You can make the column that you don't want in one table to be zero width, but this creates some other problems. For example, the user will be able to open the column you have made zero width.
My suggestion is that you use different models for each table. If you want to use the same model which somehow understands that it is delivering data to two different tables, I think you are going to have a lot of work in front of you.

Similar Messages

  • 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.

  • JTable Model   --  How to set the width of columns

    Hello,
    This project of mine is due in 2 days. :(
    I am using AbstractTableModel and I can't figure out how to set the columns' width inside my JTable?
    This following code does not work.
    int vColIndex = 1;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    int width=399;
    col.setPreferredWidth(width);Please remember, that I'm using AbstractTableModel and not just simple JTables.
    Thanks in advance.

    The DataModel (AbstractTableModel or otherwise) has nothing to do with the table column size. The DataModel is used to store data.
    When you create a JTable using a DataModel then a TableColumn is created for each column in the DataModel using a default column size. The normal order of creation would be:
    TableModel model = new DefaultTableModel(...);
    JTable table = new JTable(model);
    Now that the table and table columns are created you can change the size of the columns:
    int vColIndex = 1;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    int width=399;
    col.setPreferredWidth(width);
    So your code looks ok.
    However, if somewhere in you code you do:
    a) table.setModel(...)
    b) fireTableStructureChanged();
    then the table columns are recreated based on the current DataModel and the table column size would be reset to the default values.

  • Help updating jTable (model?)

    I've got a jTable, which stores information that I retrieve from game servers (player's name, frag count, and time connected to the server). I'll admit first off that I'm very, very new to Swing and still new to Java as a whole. I've searched the forums several times (which is the only reason I got as far as I have) and I've also closely examined the tutorial, API, and examples. I probably have already looked at my answer, but it eludes me. My table doesn't seem to be updating its display or I'm not properly modifying the object's contents because my table will only display empty cells (although the correct number of rows). Here's some snippets of what I've got so far:
    Object[][] data;
    String[] columnNames = {"Name", "Frags", "Time"};
    final DefaultTableModel model;
    data = new Object[64][3];       
    model = new DefaultTableModel(data, columnNames);
    model.setRowCount(0);
    playersListTable = new javax.swing.JTable();
    playersListTable.setModel( model );
    public void updatePlayerInfo() {
            int x = 0;
            if (settings.getServerProp("PlayerInfoNum") != null) {
                model.setRowCount(Integer.valueOf(settings.getServerProp("PlayerInfoNum")));
                while (Integer.valueOf(settings.getServerProp("PlayerInfoNum")) > x) {
                    System.out.println("Updating player info... " + x);
                    data[x][0] = settings.getServerProp("PlayerName" + x);
                    data[x][1] = settings.getServerProp("PlayerScore" + x);
                    data[x][2] = settings.getServerProp("PlayerTime" + x++);
                model.fireTableDataChanged();
        }I'm about to head off to work, so my apologies if I left out important details. I'll be around later to fill in any gaps I mistakenly forgot. Thanks again for the help!
    EDIT: The table gets updated on one second intervals.
    Edited by: mr0ldie on Nov 16, 2008 1:31 PM

    Thank you very much! :) I was very confused on how tables worked--I thought I still had to manage the data myself and the table and model were simply containers and visible settings for that (probably not explaining how I thought of it well, but I didn't fully understand, so explaining is even harder ;). Anyway, I've got it working, thanks to your help!

  • Jdbc abstract Jtable model problem

    Hi,
    I am trying to write a program that displays the content of a database in a jtable.
    So far the displaying is working, but Im having trouble with adding, deleting and modifying the jtable.
    Im working on the add method first. Its supposed to add a blank row, but it just adds the last row instead.
    Heres the source:
    // new class. This is the table model
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.JTable;
    public class MyTableModel extends AbstractTableModel {
    Connection con;
    Statement stat;
    ResultSet rs;
    int li_cols = 0;
    Vector allRows;
    Vector row;
    Vector newRow;
    Vector blankRow;
    Vector colNames;
    String dbColNames[];
    String pkValues[];
    String tableName;
    ResultSetMetaData myM;
    String pKeyCol;
    Vector deletedKeys;
    Vector newRows;
    boolean ibRowNew = false;
    boolean ibRowInserted = false;
    MyTableModel(){
    try{
    Class.forName("com.mysql.jdbc.Driver");
    catch (ClassNotFoundException e){
    System.out.println("Cannot Load Driver!");
    try{
    String url = "jdbc:mysql://localhost:3306/aubrey?";
    con = DriverManager.getConnection(url,"Dude1", "supersecret");
    stat = con.createStatement();
    rs = stat.executeQuery("SELECT * from COFFEES");
    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());
    public Class getColumnClass(int col){
    return getValueAt(0,col).getClass();
    public boolean isCellEditable(int row, int col){
    if (ibRowNew){
    return true;
    if (col == 0){
    return false;
    } else {
    return true;
    public String getColumnName(int col){
    return dbColNames[col];
    public int getRowCount(){
    return allRows.size();
    public int getColumnCount(){
    return li_cols;
    public Object getValueAt(int arow, int col){
    row = (Vector) allRows.elementAt(arow);
    return row.elementAt(col);
    public void setValueAt(Object aValue, int aRow, int aCol) {
    Vector dataRow = (Vector) allRows.elementAt(aRow);
    dataRow.setElementAt(aValue, aCol);
    fireTableCellUpdated(aRow, aCol);
    public void updateDB(){}
    public void addRow(){
         newRow.addElement(blankRow);
         int rowNumber = allRows.size();
         allRows.addElement(newRow);
         ibRowNew = true;
         this.isCellEditable(allRows.size(),0);
         System.out.println(allRows.size());
         fireTableRowsInserted(rowNumber,rowNumber);
    public void deleteRow(int i){}
    }And here is the code for the GUI:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class MyTableApp extends JFrame{
    JTable myTable;
    JButton update;
    JButton insert;
    JButton delete;
    JPanel p;
    MyTableModel tm;
    JScrollPane myPane;
    MyTableApp(){
    try{
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    catch(Exception e){
    System.out.println("Error on look and feel");
    update = new JButton("Update");
    insert = new JButton("Add");
    delete = new JButton("Delete");
    p = new JPanel();
    tm = new MyTableModel();
    myTable = new JTable(tm);
    myPane = new JScrollPane(myTable,
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    myTable.setSelectionForeground(Color.white);
    myTable.setSelectionBackground(Color.red);
    myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    p.add(myPane);
    p.add(update);
    p.add(insert);
    p.add(delete);
    update.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    tm.updateDB();
    insert.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    tm.addRow();
    myTable.setEditingRow(tm.getRowCount());
    myTable.setRowSelectionInterval(tm.getRowCount()-1,tm.getRowCount()-1);
    delete.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    int rowToDelete = myTable.getSelectedRow();
    tm.deleteRow(rowToDelete);
    myTable.setEditingRow(rowToDelete -1);
    myTable.setRowSelectionInterval(rowToDelete -1,rowToDelete -1);
    this.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    }); // end windowlistener
    this.setContentPane(p);
    this.setVisible(true);
    this.pack();
    } // constructor
    public static void main (String args[]){
    new MyTableApp();
    } // main
    } //class

    When adding a row to a JTable, one should manipulate the table model. There are many examples of this on the web. Google is your friend.
    Good luck.
    Filestream

  • How to use JTable model listener???

    Anyone got idea , how to use table model listener. Can explain in simple example with code?? how to pass back to resultset ??

    Well, your pretty good at asking questions, but not very good at thanking people for the help given to you so I don't think I'll waste too much time helping this time.
    A TableModelListener notifies you when the contents of a cell are changed. So simply take the data from the cell and update your ResultSet. You question is so general I don't know how you expect any more advice than that.

  • How to delete a JTable row without using its model

    I need to delete a row or insert a row in a JTable without using it's model. The table model for the current JTable extends AbstractTableModel so there are no defined deleteRow or insertRow methods as there are in DefaultTableModel.
    Basically, I don't know if the JTables models are going to have a deleteRow or insertRow method as all the models are AbstractTableModels and might or might not have these methods.
    Thanks.

    I interpreted "I don't have access" as meaning that there isn't a table model for that JTable. For example, you can construct a JTable this way:
    public JTable(Vector rowData, Vector columnNames)
    And the Vector of row data is what you manipulate to add or delete rows and yet you're not using a table model. If that's how your code is written then you would simply manipulate the rowdata Vector.
    However, if you mean that there is a Table model and you're not allowed to change it, then you REALLY need to get permission from your boss to change that table model. Adding a deleteRow(int) method to the TableModel wont break anything that currently exist. And to try to do an end run around the code is a nasty hack. The right way to do it is to add a method to whatever class extends AbstractTableModel and is set as the table model for this JTable.

  • How to refresh an existing row of a JTable

    Hi all,
    I have to refresh the data of an existing row of a JTable after some time in thread. The code snippet is
    DefaultTableModel model=new DefaultTableModel(data,columnNames);
    table = new JTable(model)
                   public boolean isCellEditable(int row, int col)
                   return false;
    Now I also add rows to this table within the run() of the thread as
    model.addRow(new Object []{sub1,sub6,sub12,sub3,sub18});
    My problem is that I want to refresh the data of this added row within the thread.
    Any help is highly appreciable. Thanks in advance.
    Regards,
    Har Krishan

    Hmmm. His qhestion does not seem to be with how to change the value of a field, but how to get the table to recognize the change. I thought such things were automatic. The model fires a value changed event and the JTable picks up the event and refreshes. I'm not sure why your table is not refreshing under these circumstances. Perhaps a more complete code snippet. Please use the open and close code tags to format your code if you include it.

  • Vectors and JTable

    There is 2 things I am having problems with. I have 2 vectors I need to combine. I am not sure how to combine vectors. Also I am trying to enter the information in the vectors into a JTable. I have the column names in the JTable. Here is some of the code I have now.
    //enters the column names into a vector which does display in the Jtable
    StringTokenizer stringTokenizer = new StringTokenizer(names, test);
    while(stringTokenizer.hasMoreTokens())
    columnNames.add(stringTokenizer.nextToken());
    right now I have a 2 vectors named partinfo and nsinfo. I am not sure how to combine them the information needs to line up. For the Jtable I know it needs a vector of vectors but I am not sure how to do that. Thanks for anay help.

    I am still having problems. I think I got the 2 vectors combined. I can get it to output but it displays the same entry in every row. Here is how I combined and displayed. Thanks for any help.
    for(int j=0; j <partinfo.size(); j++)
    newnsn = "";
    partinfo.elementAt(j).toString();
    tempData = (PARTS)partinfo.elementAt(j);
    nsninfo.elementAt(j).toString();
    tempSpace = (NSN)nsninfo.elementAt(j);
    newnsn = tempSpace.nsn1 +" " tempSpace.nsn2 " " tempSpace.nsn3 " " +tempSpace.nsn4;
    rowData.addElement(selectpart);
    rowData.addElement(test4);
    rowData.addElement(tempData.part);
    rowData.addElement(test4);
    rowData.addElement(test4);
    rowData.addElement(tempData.cage);
    rowData.addElement(tempData.smr);
    rowData.addElement(tempData.desc);
    rowData.addElement(newnsn);
    System.out.println(j);
    }//for
    for(int q=0; q <rowData.size(); q++)
    data.addElement(rowData);
    System.out.println(q);
    StringTokenizer stringTokenizer = new StringTokenizer(names, test);
    while(stringTokenizer.hasMoreTokens())
    columnNames.add(stringTokenizer.nextToken());
    rowData.setSize(getRowCount());
    columnNames.setSize(getColumnCount());
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    table = new JTable(model);

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • How to set cell background color for JCheckBox renderer in JTable?

    I need to display table one row with white color and another row with customized color.
    But Boolean column cannot set color background color.
    Here is my codes.
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.TreeSet;
    public class BooleanTable extends JFrame
        Object[][] data = {{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE}};
        String[] header = {"CheckBoxes"};
        public BooleanTable()
            setDefaultCloseOperation( EXIT_ON_CLOSE );
            TableModel model = new AbstractTableModel()
                public String getColumnName(int column)
                    return header[column].toString();
                public int getRowCount()
                    return data.length;
                public int getColumnCount()
                    return header.length;
                public Class getColumnClass(int columnIndex)
                    return( data[0][columnIndex].getClass() );
                public Object getValueAt(int row, int col)
                    return data[row][col];
                public boolean isCellEditable(int row, int column)
                    return true;
                public void setValueAt(Object value, int row, int col)
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
            JTable table = new JTable(model);
            table.setDefaultRenderer( Boolean.class, new MyCellRenderer() );
            getContentPane().add( new JScrollPane( table ) );
            pack();
            setLocationRelativeTo( null );
            setVisible( true );
        public static void main( String[] a )
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
            new BooleanTable();
        private class MyCellRenderer extends JCheckBox implements TableCellRenderer
            public MyCellRenderer()
                super();
                setHorizontalAlignment(SwingConstants.CENTER);
            public Component getTableCellRendererComponent(JTable
                                                           table, Object value, boolean isSelected, boolean
                                                           hasFocus, int row, int column)
                if (isSelected) {
                   setForeground(Color.white);
                   setBackground(Color.black);
                } else {
                   setForeground(Color.black);
                   if (row % 2 == 0) {
                      setBackground(Color.white);
                   } else {
                      setBackground(new Color(239, 245, 217));
                setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
             return this;
    }

    Instead of extending JCheckBox, extend JPanel... put a checkbox in it. (border layout center).
    Or better yet, don't extend any gui component. This keeps things very clean. Don't extend a gui component unless you have no other choice.
    private class MyCellRenderer implements TableCellRenderer {
        private JPanel    _panel = null;
        private JCheckBox _checkBox = null;
        public MyCellRenderer() {
            //  Create & configure the gui components we need
            _panel = new JPanel( new BorderLayout() );
            _checkBox = new JCheckBox();
            _checkBox.setHorizontalAlignment( SwingConstants.CENTER );
            // Layout the gui
            _panel.add( _checkBox, BorderLayout.CENTER );
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            if( isSelected ) {
               _checkBox.setForeground(Color.white);
               _panel.setBackground(Color.black);
            } else {
               _checkBox.setForeground(Color.black);
               if( row % 2 == 0 ) {
                  _panel.setBackground(Color.white);
               } else {
                  _panel.setBackground(new Color(239, 245, 217));
            _checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
            return _panel;
    }

  • Animated .gif in JTable cell

    Hi -
    I have an actual animated .gif that I would like to display in a JTable's cell. By 'actual animated .gif', I mean that it is one file that is animated, and not a succession of files that I would loop through to look like animation.
    I have edited the following code that I found in a previous post. My .gif does display in the JTable and animates only ONCE. Once it animates once, it stops. How can I cause it to keep looping through and repeating the animation?
    Thanks!
    Kelly
    Code below:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class AnimatedIconTableExample extends JFrame
    public AnimatedIconTableExample()
    super("AnimatedIconTable Example");
    final Object[][] data = new Object[][]
    { new ImageIcon("images/Upload.gif") }
    final Object[] column = new Object[]
    { "Image Uploading" };
    AbstractTableModel model = new AbstractTableModel()
    public int getColumnCount()
    return column.length;
    public int getRowCount()
    return data.length;
    public String getColumnName(int col)
    return (String) column[col];
    public Object getValueAt(int row, int col)
    return data[row][col];
    public Class getColumnClass(int col)
    return ImageIcon.class;
    JTable table = new JTable(model);
    table.setRowHeight(50);
    setImageObserver(table);
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
    private void setImageObserver(JTable table)
    TableModel model = table.getModel();
    int colCount = model.getColumnCount();
    int rowCount = model.getRowCount();
    for (int col = 0; col < colCount; col++)
    if (ImageIcon.class == model.getColumnClass(col))
    for (int row = 0; row < rowCount; row++)
    ImageIcon icon = (ImageIcon) model.getValueAt(row, col);
    if (icon != null)
    icon.setImageObserver(new CellImageObserver(table, row,
    col));
    class CellImageObserver implements ImageObserver
    JTable table;
    int row;
    int col;
    CellImageObserver(JTable table, int row, int col)
    this.table = table;
    this.row = row;
    this.col = col;
    public boolean imageUpdate(Image img, int flags, int x, int y, int w,
    int h)
    if ((flags & (FRAMEBITS | ALLBITS)) != 0)
    Rectangle rect = table.getCellRect(row, col, false);
    table.repaint(rect);
    return (flags & (ALLBITS | ABORT)) == 0;
    public static void main(String[] args)
    AnimatedIconTableExample frame = new AnimatedIconTableExample();
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    frame.setSize(300, 150);
    frame.setVisible(true);

    I've heard of that problem before... I think it has something to do with how the image is loaded. I found an example of how Sun does animated gifs here: http://java.sun.com/products/java-media/2D/samples/suite/Image/DukeAnim.java
    I hope it helps.

  • Store value in data model without showing it in table

    Hi,
    How can I store something in my table model without showing it in my table? I have an arraylist which contains a list of my own data objects. I have my own table model like
    public class MyTableModel extends AbstractTableModel {
                  public Object getValueAt(int row, int col) {
                   TableDataObject tdo  = (TableDataObject) data.get(row);
                   switch(col) {
                        case 0:
                             return tdo.getFoo();
                                     default:
                                             break;
    }my "hidden" value is stored in the data list...but I have to get the hidden value from my table model, not from my arraylist.

    Nothing to it, but to do it:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ColumnModelExample {
        public static void main(String[] args) {
            Object[] columnNames = {"hidden", "column 1", "column 2"};
            Object[][] rowData = {
                {"hidden 0","row 0, col 1","row 0, col 2"},
                {"hidden 1","row 1, col 1","row 1, col 2"},
            TableModel model = new DefaultTableModel(rowData, columnNames);
            JTable table = new JTable(model);
            TableColumnModel columnModel = table.getColumnModel();
            columnModel.removeColumn(columnModel.getColumn(0));
            JFrame f = new JFrame("ColumnModelExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(table));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }One typical use of this is for displaying the records of a database table, where you don't want to
    show the user a sequence column which would only confuse the user...

  • How do I add a JCheckBox to a JTable - URGENT HELP NEEDED

    Hello All,
    This is kicking my butt. I need to create a JTable that I can dynamically add and delete rows of data to and this table must contain a JCheckBox which I can read the value of. I've been able to find examples out there that provides the ability to have a JCheckBox in the JTable, but do not also provide the function to add / delete rows from the JTable. I need to have both funtions in my table. Can somebody out there please help me with this?
    Here's a simple example that I'm working with as a test to figure this out. This example has the functionality to add rows of data.
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.*;
    public class TableTest extends JFrame implements ActionListener
         JButton btnAdd;
         BorderLayout layout;
         DefaultTableModel model;
         public static void main(String[] args)
              TableTest app = new TableTest();
              app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TableTest()
              super("Table Example");
              layout = new BorderLayout();
              Container container = getContentPane();
              container.setLayout(layout);
              btnAdd = new JButton("Add");
              btnAdd.addActionListener(this);
              model = new DefaultTableModel();
              JTable table = new JTable(model);
              // Create a couple of columns
              model.addColumn("Col1");
              model.addColumn("Col2");
              // Append a row
              model.addRow(new Object[] { "v1", "v2" });
              model.addRow(new Object[] { "v3", "v4" });
              JScrollPane scrollPane = new JScrollPane(table);
              container.add(btnAdd, BorderLayout.NORTH);
              container.add(scrollPane,BorderLayout.CENTER);
              setSize(300, 200);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnAdd)
                   model.addRow(new Object[]{"Test", new Boolean(true)});
    }

    I got it, I added the public Class getColumnClass to new DefaultTableModel(). Here it is for your viewing pleasure.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.*;
    public class TableTest extends JFrame implements ActionListener
         JButton btnAdd;
         BorderLayout layout;
         DefaultTableModel model;
         JTable table;
         public static void main(String[] args)
              TableTest app = new TableTest();
              app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TableTest()
              super("Table Example");
              layout = new BorderLayout();
              Container container = getContentPane();
              container.setLayout(layout);
              btnAdd = new JButton("Add");
              btnAdd.addActionListener(this);
              model = new DefaultTableModel()
                   public Class getColumnClass(int col)
                        switch (col)
                             case 1 :
                                  return Boolean.class;
                             default :
                                  return Object.class;
              table = new JTable(model);
              // Create a couple of columns
              model.addColumn("Col1");
              model.addColumn("Col2");
              // Append a row
              model.addRow(new Object[] { "v1", new Boolean(false)});
              model.addRow(new Object[] { "v3", new Boolean(false)});
              JScrollPane scrollPane = new JScrollPane(table);
              container.add(btnAdd, BorderLayout.NORTH);
              container.add(scrollPane, BorderLayout.CENTER);
              setSize(300, 200);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnAdd)
                   model.addRow(new Object[] { "Karl", new Boolean(true)});

  • Selecting cells in a JTable

    Hi All,
    I'm looking for a way of selecting all cells from the original drag point to the current cell that the mouse is over.
    This is for a year planner which displays the months vertcally and the days horizontally. So if the user was to start selecting cells in one month and move the mouse down a row onto the next month, I would want all cells selected from the first cell to the current cell.
    Has anyone got any ideas?

    Hi Pchatwin,
    Any dukes available for bad news? :)
    Thanks Stas but wouldn't that select entire rows
    rather than cells?
    For example, if I have a grid:
    12345
    67890
    and drag from cell 3 to cell 9 I would need to see
    cells 3, 4, 5, 6, 7, 8, 9 highlightedUnfortunately this is impossible with JTable's default selection model. By default, JTable models selections simply as an intersection of selected rows and columns. It doesn't track individual cells.
    Turning to your example:
    If you select cells 2,3,4,5 JTable tracks the following.
    Note: The numbers I am using are row/col indexes, not your cell values.
    Selected rows = {0}
    Selected cols = {1,2,3,4}
    This means the following cells are selected:
    {{0,1},{0,2},{0,3},{0,4}} or {2,3,4,5}
    Now if you want to add cells 6, 7, 8, 9 it won't work. The selection model tracks whether a column is selected or not. It can't be selected for one row and not for another. So it's impossible to have cell 6 selected and not 1. It would mean that column 0 would need to be both selected (to include 6) and not (to include 1). Does this make sense?
    Sorry to have to tell you that. On the other hand it may save you some frustration.
    Oh, and whether or not one can provide a custom model that allows this, I don't know - I've not tried it myself. It could be, but might be very difficult. For example, what would you return from JTable.getSelectedRows()?
    Thanks!
    Shannon Hickey (Swing Team)
    >
    Paul

Maybe you are looking for