Images in JTable

Hi,
The Problem:
Instead of the Image i see the image's filename.
The Question:
Which is the simplest way to display an Image in a JTable?

Hi.. mathuoa
You can set the row height as:
table.setRowHeight(300);
Here's the abstract table model implementaion e.g.
* Implementation of abstract table model for displaying Image(s) in table
* Cell grid.
* @version 1.0 10 Sep 2002
* @author Md. Ash-Shakur Rahaman (mailto: [email protected])
class GridImageTableModel extends AbstractTableModel{
/** Number of rows */
static int rows;
/** Number of columns*/
static int cols;
/** table data */
public static Object[][] rowData;
/**column names */
String[] colNames;
* Constructor
* @param     rd     row data as 2D Object array
* @param     cn     column names as 1D String array
public GridImageTableModel(Object[][] rd, String[] cn){
this.rowData = rd;
this.colNames = cn;
* gets the number of rows available of the table
* @param     nothing no parameter is required
* @return rows     returns the rows count as int
public int getRowCount(){
this.rows = rowData.length;
return rows;
* gets the number of columns available of the table
* @param     nothing     no parameter is required
* @return cols     returns the column count as int
public int getColumnCount(){
this.cols = colNames.length;
return cols;
* gets the data at particular row & column
* @param     row     at which row
* @param     col     at which column
* @return rowData the data as 2D Object array
public Object getValueAt(int row, int col){
return rowData[row][col];
* gets the class name of a particular column
* @param     c     column number for which the class names is to be determined
* @return     class     returns the class name of the column
public Class getColumnClass(int c){
return getValueAt(0,c).getClass();
* gets the column cell editable or non editable
* @param row     which row
* @param col     which column
* @return editable true if editable;
* false otherwise     
public boolean isCellEditable(int row, int col){
return true;
* sets the value at particular row-column
* @param value     value to be inserted
* @param row     at which row
* @param col     at which column
* @return nothing
public void setValueAt(Object value, int row, int col){
rowData[row][col] = value;
fireTableCellUpdated(row,col);
* Implementation of Default table column model for displaying Image(s) in table
* Cell grid.
* @version 1.0 10 Sep 2002
* @author Md. Ash-Shakur Rahaman (mailto: [email protected])
class GridImageTableColModel extends DefaultTableColumnModel{
/**column names*/
String [] colNames;
/**column counter*/
static int counter=0;
* GridImageTableColModel constructor with column names
* @param cn coumn names as 1D String array
public GridImageTableColModel(String[] cn){
this.colNames = cn;
* adds column to the table
* @param tc table column
* @return nothing
public void addColumn(TableColumn tc){
// if counter is equal to the number of column then reset counter to zero
if (counter == 1) counter=0;
tc.setHeaderValue(DataStoreUnit.grdimgColumnNames[counter]);
tc.setResizable(false);
super.addColumn(tc);
counter+=1;
Use this as follwoung manner:
//Grid Image Table Implementation
final static String[] grdimgColumnNames = {"Image(s)"};
// Initial data to be displayed in the table
final Object[][] grdimgData = {{""}};
//Grid Image Table Model: Table to display the data
TableModel grdimgTableModel = new GridImageTableModel(grdimgData,grdimgColumnNames);
//Grid text Table Header
JTableHeader grdimgTableHeader = new JTableHeader();
// Grid image Column Model
TableColumnModel grdimgTableColumnModel = new GridImageTableColModel(grdimgColumnNames);
// Grid Image Table
JTable grdimgtable = new JTable(grdimgTableModel);
JScrollPane jspGridImageTable = new JScrollPane();
int tab = grdimgtable.AUTO_RESIZE_ALL_COLUMNS;
grdimgTableHeader.setResizingAllowed(false);
grdimgTableHeader.setBackground(new Color(0, 0, 239));
grdimgTableHeader.setForeground(Color.white);
grdimgTableHeader.setFont(font);
grdimgTableHeader.setColumnModel(grdimgTableColumnModel);
grdimgtable.setTableHeader(grdimgTableHeader);
grdimgtable.createDefaultColumnsFromModel();
grdimgtable.sizeColumnsToFit(tab);
grdimgTableHeader.setReorderingAllowed(false);
grdimgtable.setRowHeight(300);
/**render the first cell in the table*/     
grdimgTableCellRender(grdimgtable.getColumnModel().getColumn(0));
grdimgtable.setPreferredSize(new Dimension(32767,32767));
jspGridImageTable.getViewport().add(grdimgtable, null);
grdimgtable.setBorder(new LineBorder(Color.blue));
I think now you can work...Go ahead..
Rana

Similar Messages

  • Insert an image in JTable

    hi all
    how can i insert an image in JTable instead of text in a row?
    angela

    Hi
    I am sending u two bits of codes
    execute these and let me know
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class FrozenTable extends JScrollPane {
    public FrozenTable()
    TableModel tableModel = new AbstractTableModel()
    public String getColumnName(int col) { return "Column " + col; }
    public int getColumnCount() { return 20; }
    public int getRowCount() { return 40;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    JTable table1 = new JTable(tableModel);
    JTable table2 = new JTable(tableModel);
    TableColumnModel columnModel = table1.getColumnModel();
    TableColumnModel columnModel2 = new DefaultTableColumnModel();
    TableColumn col1 = columnModel.getColumn(0);
    TableColumn col2 = columnModel.getColumn(1);
    columnModel.removeColumn(col1);
    columnModel.removeColumn(col2);
    columnModel2.addColumn(col1);
    columnModel2.addColumn(col2);
    for(int i = 0; i < 2; i++)
    TableColumn col = columnModel2.getColumn(i);
    col.setWidth(80);
    col.setMinWidth(80);
    table2.setColumnModel(columnModel2);
    table2.setPreferredScrollableViewportSize(table2.getPreferredSize());
    table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table1.getTableHeader().setUpdateTableInRealTime(false);
    table2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table2.getTableHeader().setUpdateTableInRealTime(false);
    table2.getColumnModel().getColumn(0).setCellRenderer( new ColorRenderer(0) );
    table2.setBorder(new CompoundBorder(new MatteBorder(0,0,0,1,Color.black), table2.getBorder()));
    setViewportView(table1);
    setRowHeaderView(table2);
    setCorner(JScrollPane.UPPER_LEFT_CORNER, table2.getTableHeader());
    public static void main(String[] args)
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    FrozenTable table = new FrozenTable();
    panel.setLayout(new GridLayout(1,1));
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);
    class yourClass extends JLabel implements TableCellRenderer
         int selectedRow = 0;
         public yourClass ()
              super();
              setOpaque(true);
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
              try
                   setIcon(new ImageIcon("image.gif") );          
              }catch(Exception e) {  }
              return this;
    Cheers :)
    Nagaraj

  • How to display non-URL-based thumbnail images in JTable

    I'm trying to display thumbnail images as a tooltip popup for certain cells in a JTable. The thumbnail images are java image objects that have been retrieved dynamically as the result of a separate process--there is no associated URL. For this reason, I can't use the setToolTipText() method of the JTable.
    My attempts to JTable's createToolTip() method also failed as it seems the ToolTipManager never calls this method for a JTable.
    As a workaround, I've added a MouseMotionListener to the JTable that detects when the mouse is over the desired table cells. However, I'm not sure how to display the popup over the JTable. The only component that I can get to display over the JTable is a JPopupMenu, but I don't want to display a menu--just the image. Can anyone suggest a way to display a small popup image over the table?
    Thanks.

    Thank You Rodney. This explains why my createToolTip() method wasn't being called, but unfortunately I'm no closer to my goal of displaying a true custom tooltip using a non-URL image rather than a text string. If I make a call to setToolTipText(), at any point, the text argument becomes the tooltip and everything I have tried in createToolTip() has no effect. However, as you pointed out, if I don't call setToolTipText(), the table is not registered with the tooltip manager and createToolTip() is never even called.
    To help clarify, I have attached an SSCCE below. Please note that I use a URL image only for testing. In my actual application, the images are available only as Java objects--there are no URLs.
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    public class Test {
        static Object[][] data = {
                {"Cell 0,0", "Cell 0,1"},
                {"Cell 1,0", "Cell 1,1"}};
        static String[] columnNames = {"Column 0", "Column 1"};
        static JFrame frame;
        static String testImageURLName = "http://l.yimg.com/k/omg/us/img/7c/0a/4009_4182164952.jpg";
        static JTable testTable = new JTable(data, columnNames) {
            public JToolTip createToolTip() {
                System.out.println("testTable.createToolTip() called");
                Image testImage = getTestImage();
                // this.setToolTipText("Table ToolTip Text");
                JLabel customTipLabel = new JLabel(new ImageIcon(testImage));
                customTipLabel.setToolTipText("Custom ToolTip Text");
                JToolTip parentTip = super.createToolTip();
                parentTip.setComponent(customTipLabel);
                return parentTip;
        // This image is loaded from a URL only for test purposes!!!
        // Ordinarily, the image object would come from the application
        // and no URL would be available.
        public static Image getTestImage() {
            try {
                URL iconURL = new URL(testImageURLName);
                ImageIcon icon = new ImageIcon(iconURL);
                return icon.getImage();
            catch (MalformedURLException ex) {
                JOptionPane.showMessageDialog(frame,
                        "Set variable \"testImageName\" to a valid file name");
                System.exit(1);
            return null;
        public static void main(String[] args) throws Exception {
            frame = new JFrame("Test Table");
            frame.setSize(300, 100);
            // Set tool tip text so that table is registered w/ tool tip manager
            testTable.setToolTipText("main tooltip");
            frame.getContentPane().add(testTable);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }

  • Drag and Drop Image into JTable

    I was wondering if anyone can tell me if it is possible to have an image dragged and dropped into a JTable where the single image snaps to multiple columns and rows?
    Thank you.

    Can anyone point me in the right direction for doing the following:
    Drag and drop an image into a JTable where the single image snaps to multiple columns and rows.
    Thanks.

  • Adding  images in  JTable !

    Hello all !
    I have a database with a table which contains information about an image and the PATH for it. I want display the database table in a JTable but I don't know how i can display the Image in a Jtable if I had the path of it in a database.

    f.getContentPane().add(new JScrollPane(new JTable(adaptor){
    public Class getColumnClass(int column)
    return getValueAt(0, column).getClass();
    i have the path inside the column six not the first sorry!
    sorry for this message It's late and i am very tired
    i have i9n database a filed whish contains :
    new ImageIcon ("c:\x\x\xyz.jpg")
    and i tried to change the renderer whith
    f.getContentPane().add(new JScrollPane(new JTable(adaptor){
    public Class getColumnClass(int column)
    return getValueAt(0, column).getClass();
    i don't know where is mistake?
    Message was edited by:
    aurelian_cl

  • Place image in jtable

    Hello I want to place an image in a jtable.
    How can I do this because when I tried it I only saw the link to the file

    There are two things you need to to:
    a) use an Icon as your data for a column
    b) tell the table what type of data you are using for each column:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              ImageIcon aboutIcon = new ImageIcon("about16.gif");
              ImageIcon addIcon = new ImageIcon("add16.gif");
              ImageIcon copyIcon = new ImageIcon("copy16.gif");
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {aboutIcon, "About"},
                   {addIcon, "Add"},
                   {copyIcon, "Copy"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              //  Set the first column to use a combobox as its editor
              Object[] items = { aboutIcon, addIcon, copyIcon };
              JComboBox editor = new JComboBox( items );
              DefaultCellEditor dce = new DefaultCellEditor( editor );
              table.getColumnModel().getColumn(0).setCellEditor(dce);
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • Image In JTable

    Hi all
    I want to display an Image in the cell of the JTable.
    I defined already a cellRenderer for the table ( not for colum ) for component.
    but for exampele, If I want that cell (0,0) will be JButton ( which now its working good ) and cell (1,0) wiil display an Image, what can I do? define another cell renderer????
    thank`s ppl

    here is my code for the renderer:
    class XTableCellRenderer implements TableCellRenderer
    //implement getTableCellRendererComponent method from the TbleCellRenderer interface
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
    //if the " value " that we got is inherited from component ( it button,label,etc...)
    //then it casting to component and send back else return null
    if ( value instanceof Component)
    return(Component)value ;
    else
    return null;
    its return component (or null), so how can I draw an Image, if the cell contain it?

  • Displaying image in JTable gets me nothing

    Hi everyone,
    I created a subclass of JTable which's TableModel is a subclass of AbstractTableModel. My table is supposed to display images in one of the columns but for some reasons I got nothing displayed in that column. I made the column editable so I can check wheter cells are holding something and when I double click any cell of this column I get the path to the image displayed so I know it's there. When I change the getColumnClass for it to return the String class the path to the image is also displayed.
    Here's the code of the getColumnClass function :
         @Override
         public Class<?> getColumnClass(int columnIndex) {
              Class<?> c = String.class;
              if( columnIndex == 2 ){
                   return ImageIcon.class;
              else if( columnIndex == 4 ){
                   c = JComboBox.class;
              return c;
         }Any idea of what I did wrong ?
    Julien

    Julien_Java_Developer wrote:
    Any idea of what I did wrong ?
    JulienYup. You didn't post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html], so we don't know what data is in your table model, we don't know whether you're silintly swallowing any exceptions, we don't know ...
    Heck, we don't know anything that might help us to suggest a fix.
    Also, it looks like you're storing JComboBoxes in the model, which isn't a good idea.
    db

  • Background Image in JTable headers

    Hi
    I used the following article http://java.sun.com/products/jfc/tsc/articles/swing2d/index.html
    to create a background image in my java application and then also how to make the table "see through".
    I have managed this apart from one small problem. The tabele headers appear white.
    I have tried everything but with no success. Please help. Below is the code i am using for the header
    JTableHeader tableHead;
    DefaultTableCellRenderer header = new DefaultTableCellRenderer() {
    boolean isSelected = false;
    Color selectionColor;
    // we'll use a translucent version of the table's default
    // selection color to paint selections
    Color oldCol = table.getSelectionBackground();
    selectionColor = new Color(oldCol.getRed(), oldCol.getGreen(), oldCol.getBlue(), 128);
    // need to be non-opaque since we'll be translucent
    setOpaque(false);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    // save the selected state since we'll need it when painting
    this.isSelected = isSelected;
    if (table != null) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
    header.setResizingAllowed(false);
    header.setReorderingAllowed(false);
    setForeground(Color.black);
    setHorizontalAlignment(CENTER);
    setFont((new java.awt.Font("Dialog", 1, 14)));
    setHorizontalAlignment(CENTER);
    setFont((new java.awt.Font("Dialog", 1, 14)));
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    // since DefaultTableCellRenderer is really just a JLabel, we can override
    // paintComponent to paint the translucent selection when necessary
    public void paintComponent(Graphics g) {
    if (isSelected) {
    g.setColor(selectionColor);
    g.fillRect(0, 0, getWidth(), getHeight());
    super.paintComponent(g);
    table.getTableHeader().setDefaultRenderer(header);

    This thread shows the easiest way I've found to paint a background image on a component:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=316074
    However, a JTableHeader will be a little more difficult since it uses the renderer to paint each cell. The renderer must be made opaque to the image can be seen:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableHeaderImage extends JFrame
        ImageIcon icon = new ImageIcon("mong.jpg");
        public TableHeaderImage()
            JTable table = new JTable(5, 5);
            JTableHeader header = new JTableHeader( table.getColumnModel() )
                public void paintComponent(Graphics g)
                    //  Scale image to size of component
                    Dimension d = getSize();
                    g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
                    setOpaque( false );
                    super.paintComponent(g);
            ((JComponent)header.getDefaultRenderer()).setOpaque(false);
            table.setTableHeader( header );
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
        public static void main(String[] args)
            JFrame frame = new TableHeaderImage();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • Styled text+Image in JTable

    Hi all java guru...
    I have a JTable and i would like to add dynamically in any cell styledText (e.g. bold,underline,italics,etc) and image with the features to align styledText on left/right of the image.
    I think that i must use CustomTableModel to maintain styledText information and some CustomTableCellRenderer clas that handles my cells. Is this correct? If somebody have already had this problem please can help me? Or drive me in some example that can help me.
    Can i realize it using DefaultTableModel only ??
    Thanks in advance.
    Cheers.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        Font font1 = new Font("TimesRoman", Font.BOLD, 14);
        Font font2 = new Font("SansSerif", Font.ITALIC, 12);
        Font font3 = new Font("Tehoma", Font.PLAIN, 16);
        MyObject[][] data = {{new MyObject("Hello", font1),
            new MyObject("There", font2),new MyObject("anti-shock", font3)}};
        JTable jt = new JTable(data,head);
        jt.setDefaultRenderer(Object.class, new MyRenderer());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] args) { new Test(); }
    class MyObject {
      String str;  Font font;
      public MyObject (String s, Font f) { str=s; font=f; }
      public String toString() { return str; }
      public Font getFont() { return font; }
    class MyRenderer extends DefaultTableCellRenderer {
      Font defaultFont = new Font( "Dialog" , Font.PLAIN, 12);
      public Component getTableCellRendererComponent(JTable table, Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row, int column) {
        Component c = super.getTableCellRendererComponent(table,value,
            isSelected,hasFocus,row,column);
        if (value instanceof MyObject) c.setFont(((MyObject)value).getFont());
        else c.setFont(defaultFont);
        return c;
    }

  • Problem in adding image in jtable cells

    hi all.
    im creating a swing application using netbeans 6.0.
    i want to display image in cells of one column.
    for that i set an "image icon" directly to that cell in the "default table model", in that case it is displaying the path of that image in that cell!
    then i created a new label, and set the image as icon of that label. added that label in that cell. in this case it is printing label.tostring() to that cell!!
    please help.
    thanks in advance.

    You need to override getColumnClass to return Icon.class for the column containing the icon. A code snippet that demonstrates how you might do this:      table = new JTable (new DefaultTableModel (data, colNames) {
             public Class getColumnClass (int columnIndex) {
                switch (columnIndex) {
                   case 0: return Calendar.class;
                   case 1: return String.class;
                   case 2: return Icon.class;
                   //case 2: return Boolean.class;
                return null;
          });luck, db

  • Draw image over jtable header

    hello, I am trying to draw an image (its a little image of a custom sort indicator) over the header of a jTable, but after extensive reading of the api docs about TableCellRenderer and DefaultTableCellRenderer I cannot come to a solution.
    What I want is something like this: let the renderer do the paint and after that I grab the graphics and draw the image over it...
    please let me know if I need to restate my problem

    I extended DefaultTableCellRenderer like you say in your article, but while doing so it lost the default Metal L&F. It become like an ordinary cell of the table. Below is the code:
    class DefaultTableHeaderCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
       @Override
       public Component getTableCellRendererComponent(JTable table, Object value,
             boolean isSelected, boolean hasFocus, int row, int column)
          super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, column);
          //setIcon(getIcon(table, column));
          setBorder(UIManager.getBorder("TableHeader.cellBorder"));
          return this;
        protected Icon getIcon(JTable table, int column) {
           ImageIcon icon = new ImageIcon("imagens/sortdown.png");
           return icon;
    }then in my class I call:
    this.getTableHeader().setDefaultRenderer(new DefaultTableHeaderCellRenderer());You can see I commented setIcon. It works, the icon is drawn, but this is not what I am after, I wanted to draw the icon over the Metal L&F. Also, is there a way to draw the icon at a specified position?
    thanks for the help

  • Adding Image in JTable - help needed(Urgent).

    Hai Friends,
    i want to add two icon in the cells of JTable... i dont know where am going wrong... the icon is not getting displayed in the cell but instead if i double click the cell the name of the icon is displayed in editable mode... any suggestion...
    this is my code... i got this from the forum only... but tis not working....
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {new ImageIcon("juggler.ico"), "Copy"},
                   {new ImageIcon("favicon.gif"), "Add"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
          System.out.println("getValueAt(0, column)"+getValueAt(0, 0));
                        return getValueAt(0, 0).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }Urgent... pls help...
    Regards,
    Ciya.

    Hai Chris,
    Thanks for ur reply,
    Now Its throwing null pointer exception in the URL....
    Can u pls look into d code and tell me pls...
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.net.URL;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellRenderer;
    public class MyIcon extends JPanel
      private JScrollPane jScrollPane1 = new JScrollPane();
      private JTable jTable1;
      private GridBagLayout gridBagLayout1 = new GridBagLayout();
      public MyIcon()
        try
          jbInit();
        catch(Exception e)
          e.printStackTrace();
      private void jbInit() throws Exception
        this.setLayout(gridBagLayout1);
        jTable1 = new JTable(new AbstractTableModel()
         URL lURL = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
          URL lURL2 = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
        Object[][] data =
            {new ImageIcon(lURL), "Copy"},
            {new ImageIcon(lURL), "Add"},
          public int getRowCount()
            return 2;
         public int getColumnCount()
           return 2;
         public Object getValueAt(int row, int column)
           return data[row][column];
        jTable1.getColumnModel().getColumn(0).setCellRenderer(new Renderer());
        jScrollPane1.getViewport().add(jTable1, null);
        this.add(jScrollPane1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(60, 20, 125, 25), -97, -287));
      public static void main(String a[])
        MyIcon c = new MyIcon();
        JFrame f = new JFrame();
        f.getContentPane().add(c);
        f.setSize(400,400);
        f.setVisible(true);
      class Renderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column) {
    setIcon((ImageIcon) value);
    return this;
    }Ciya...

  • How to add image in jtable header using 'Default table model'

    Hi,
    I created a table using "DefaultTableModel".
    im able to add images in table cells but not in 'table header'.
    i added inages in table by overriding "getColumnClass" of the DefaultTableModel.
    But what to do for headers?
    please help.
    Thanks in advance.

    The 'Java 5 tutorial' is really an outstanding oneI should note the the current tutorial on the Sun website has bee updated for Java 6. It contains updates to reflect the changes made in JDK6. Once of the changes is that sorting of tables is now supported directly which is why I needed to give you the link to the old tutorial.
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html

  • How to display images in a Jtable cell-Urgent

    Hay all,
    Can anybody tell me that can we display images to JTable' cell,If yes the how do we do that(with some code snippet)? Its very urgent .Plz reply as soon as possible.

    Here is an example
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class SimpleTableExample extends JFrame
         private     JPanel  topPanel;
         private     JTable  table;
         private     JScrollPane scrollPane;
         public SimpleTableExample()
              setTitle( "Table With Image" );
              setSize( 300, 200 );
              setBackground( Color.gray );
              topPanel = new JPanel();
              topPanel.setLayout( new BorderLayout() );
              getContentPane().add( topPanel );
              // Create columns names
              String columnNames[] = { "Col1", "Col2", "Col3" };
              // Create some data
              Object data[][] =
                   { (ImageIcon) new ImageIcon("User.Gif"), (String) "100", (String)"101" },
                   { (String)"102", (String)"103", (String)"104" },
                   { (String)"105", (String)"106", (String)"107" },
                   { (String)"108", (String)"109", (String)"110" },
              // Create a new table instance
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              };          // Add the table to a scrolling pane
              scrollPane = new JScrollPane( table );
              topPanel.add( scrollPane, BorderLayout.CENTER );
         public static void main( String args[] )
              SimpleTableExample mainFrame     = new SimpleTableExample();
              mainFrame.setVisible( true );
    }

Maybe you are looking for