Skip to content
June 30, 2010 / Narayan

Adding JLabel in JTable

Hello guys,

This post is related to the Swing of Java. Mostly in JTable we can see that we need the icons in a table for the reliability and RIA of software for the front-end user. So to use icon we used to import the .png/.jpg/.gif in our project. Firstly you need to know how the JTable cell are being rendered and we need to know the model of the JTable.

You can refer to the api:

Ok now let’s move to the main Job.

We need to know which one column is need to place an icon. Futher more the table must be made from our own custom Table Model. Not only that we need to add a table cell renderer . Our main motto is to add a JLabel in a Cell of JTable. After you have referred to the API it would be easier to deal with the cell renderer. This cell renderer can be obtained by extending DefaultTableCellRenderer.

Source Code for CellRenderer:


import javax.swing.JLabel;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class Renderer extends DefaultTableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
         boolean hasFocus, int row, int column)
     {

        if(value instanceof JLabel){
           //This time return only the JLabel without icon
            return (JLabel)value;
        }

        else
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

     }
}

In the same way i’ll create a extended DefaultTableModel


import javax.swing.JLabel;

class MyModel extends javax.swing.table.DefaultTableModel{

    Object[][] row = {{new JLabel("Row 1 Col 1"), "Row 1 Col 2", "Row 1 Col3"},
                      {new JLabel("Row 2 Col 1"), "Row 2 Col 2", "Row 2 Col3"},
                      {new JLabel("Row 3 Col 1"), "Row 3 Col 2", "Row 3 Col3"},
                      {new JLabel("Row 4 Col 1"), "Row 4 Col 2", "Row 4 Col3"}};

    Object[] col = {"Column 1", "Column 2", "Column 3"};

    public MyModel (){

	//Adding columns
        for(Object c: col)
            this.addColumn(c);

	//Adding rows
        for(Object[] r: row)
            addRow(r);

    }

    @Override

    public Class getColumnClass(int columnIndex) {
        if(columnIndex == 0)return getValueAt(0, columnIndex).getClass();

        else return super.getColumnClass(columnIndex);

    }

}

Now we’ll create a small app extending JFrame and utilizing the above classes.


import javax.swing.*;
import ftp.gui.IconTableCellRenderer;

public class MyTableTest extends JFrame{
    public MyTableTest(String title){

        super(title);
        showGUI();

    }

    public void showGUI(){

        JTable table = new JTable();
        table.setModel(new MyModel());//invoking our custom model
        table.setDefaultRenderer(JLabel.class,  new Renderer());// for the rendering of cell
        JScrollPane jp = new JScrollPane(table);
        getContentPane().add(jp);
        setVisible(true);
        setSize(500,300);

    }

    public static void main(String[] args) {
        MyTableTest t = new MyTableTest("Table Custom");
    }

}

After all the output must be like this:

Output

To make the JLabel selected as other cell of JTable.

For this you need to add some more code in Cell Renderer.

Modified Cell Renderer for selection of JLabel

import javax.swing.JLabel;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class Renderer extends DefaultTableCellRenderer{

    public void fillColor(JTable t,JLabel l,boolean isSelected ){
        //setting the background and foreground when JLabel is selected
        if(isSelected){
            l.setBackground(t.getSelectionBackground());
            l.setForeground(t.getSelectionForeground());
        }

        else{
            l.setBackground(t.getBackground());
            l.setForeground(t.getForeground());
        }

    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
         boolean hasFocus, int row, int column)
     {

        if(value instanceof JLabel){
            JLabel label = (JLabel)value;
            //to make label foreground n background visible you need to
            // setOpaque -> true
            label.setOpaque(true);
            fillColor(table,label,isSelected);
            return label;

        }

        else
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
     }

}

Now the output must be something like this:

output

To add Icon on JTable Cell

For adding icon on JTable you can simply add a line of code in your Renderer.

I’ve just added one line code in the above DefaultTableCellRender extended class i.e. Renderer


//In the method of getTableCellRendererComponent

        if(value instanceof JLabel){
            JLabel label = (JLabel)value;
            //you can add the image here
            label.setIcon(new ImageIcon(getClass().getResource("folder.png")));
            label.setOpaque(true);
            fillColor(table,label,isSelected);

            return label;
        }

//other stuff

Output:

output with icon

That’s all for today.

Thanks you and Don’t hasitate on giving comment.

Advertisements

11 Comments

Leave a Comment
  1. dis / Jul 7 2010 12:48 pm

    thanks. You saved me from googling for hours.
    minor fix: listing 2 line 10. replace TableTest with MyModel

  2. WangLili / Jan 20 2011 7:27 am

    Way too complicated. This way is simpler:

    For a given column:

    TableColumn someColumn = table.getColumnModel().getColumn(0);
    someColumn.setCellRenderer(IconifiedRenderer(new ImageIcon(getClass().getResource("/images/ic.png"))) );

    //file: IconifiedRenderer.java

    public class IconifiedRenderer extends DefaultTableCellRenderer {
    Icon ic = null;

    public IconifiedRenderer(Icon ic) {
    this.ic = ic;
    }

    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus, int row,
    int column) {

    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    setIcon(ic);
    return this;
    }

    }

    • Narayan / Jan 23 2011 11:13 am

      hi wang,
      Ya it’s good and simple for icon cell !!But lil bit mistake..
      TableColumn someColumn = table.getColumnModel().getColumn(0);
      someColumn.setCellRenderer(new IconifiedRenderer(new ImageIcon(getClass().getResource(“/images/ic.png”))) );

      Thanks..for comment !

  3. Kleopatra / Jun 13 2011 11:12 am

    completely wrong approach: never-ever add a component to the model! Instead (as already suggested) store the icon.

  4. Narayan / Jun 29 2011 3:38 am

    hi Kleopatra,

    The icon is stored as a resource where it needs to be. Every Table Model has the getTableCellRendererComponent and I think you probably thinking why I’m using new ImageIcon everytime,After all it’s just a sample example which don’t cares of performance.

  5. Ami / Jul 12 2011 3:03 pm

    How about adding a tooltip to th icon? How to achieve that here?

  6. poornima / Oct 21 2011 5:35 pm

    GREAT HELP 🙂 THANKS

  7. basavaraj / Sep 7 2012 12:33 pm

    I NEED THIS HELP AS SOON AS POSSIBLE. I HAVE A JAVA SWING TABLE WHERE I AM DISPLAY KANNADA UNICODE FONTS. THIS ಶ್ರೀರಂಗಪಟ್ಟಣ THING IN NOTE PAD IS COMING CORRECT BUT WHEN I AM READING AND DISPLAY IN THE SWING TABLE IT IS COMING AS ಶ್ರಿ ೕರಂಗಪಟ್ಟಣ . PLEASE FIND ME A SOLUTION. I M USING ARIAL UNICODE MS FONT TO DISPLAY. ITS URGENT PLEASE HELP ME. I HAVE TRIED BELOW MENTIONED THINGS.
    1. I HAVE INSTALLED THE FONTS IN OS AND AS WELL AS JRE-LIB-FONT DIRECTORY
    2. I HAVE TRIED TO CHANGE UTF-8 TO ISO. BUT THEN AGAIN NOT WORKING
    3. I HAVE TRIED OTHER 10 DIFFERENT KANNADA UNICODE FONTS. BUT NONE OF THEM ARE WORKING

    • Narayan / Sep 8 2012 5:54 pm

      hi basavaraj,
      From which source are you reading this UNICODE text to Java?
      If you are reading from any stream then please use direct InputStream instead of BufferedReader or other.
      If you are using normal string value then use “\u001\u002” kind of string instead of direct string.

      Thanks

Trackbacks

  1. Vector handling:Extracting Object from a Vector in Java « Wise Notes for Students

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: