Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Icon

Posted on 2001-06-20
15
389 Views
Last Modified: 2010-04-16
Hi..All,
         one more query from here...
How do i add Icon dynamically to JTable...
like...i want to add Dir Icon and File Icon in my JTable...pls..give me some suggestion....

Regards,
Thazim
0
Comment
Question by:thazim
  • 11
  • 4
15 Comments
 
LVL 9

Expert Comment

by:Ovi
ID: 6213002
I will make you the code ... in short time.
0
 

Author Comment

by:thazim
ID: 6213093
Hi..guys/gals,

        This code help me to add icon but...the problem is...i want to do this for some other table where i'll get dyanmically files and
Dirs....where i want to add......Icons...
so..pls..help me in this.....

import javax.swing.table.*;
import javax.swing.*;
import java.awt.*;

public class IconTable {

static IconRenderer renderer = new IconRenderer();

public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();

TableModel tableModel = new AbstractTableModel()
{
public int getColumnCount() { return 10; }
public int getRowCount() { return 25;}
public Object getValueAt(int row,int col)
{
if(col == 0 )
return "testing.txt";
else
return "testing.doc";
}
};

JTable table = new JTable(tableModel);
JScrollPane pane = new JScrollPane(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnModel columnModel = table.getColumnModel();
for(int i = 0; i < columnModel.getColumnCount(); i++)
{ columnModel.getColumn(i).setCellRenderer(renderer); }

panel.add(pane);
frame.getContentPane().add(panel);
frame.setSize(500,500);
frame.setVisible(true);
}
}

class IconRenderer extends DefaultTableCellRenderer {

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
String headerText = (String)value;
JLabel headerComponent = ((JLabel)super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column));
if(headerText.indexOf(".txt") != -1) { headerComponent.setIcon(new ImageIcon("settings.gif")); }
if(headerText.indexOf(".doc") != -1) { headerComponent.setIcon(new ImageIcon("Print.gif")); }
return headerComponent;
}
}
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213094
Is coming
0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 9

Accepted Solution

by:
Ovi earned 100 total points
ID: 6213103
Make sure that you have in the directory where you will store this source file two images called 'folder.gif' and 'file.gif'. If your compilation output is in other directory different from that where the source is stored, copy the images there too. After that create some dummy directories and files, and enjoy.

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class FileSystemView extends JFrame {
  private SystemView table;

  public FileSystemView() {
    getContentPane().setLayout(new BorderLayout());
    setSize(400, 300);
    setLocation(300, 100);
    table = new SystemView();
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    setVisible(true);
  }

  class SystemView extends JTable {
    SystemViewModel model;

    public SystemView() {
      model = new SystemViewModel();
      setAutoCreateColumnsFromModel(false);
      loadDefaultData();
      setModel(model);
      createColumns();
      setGridColor(Color.white);
      setForeground(Color.black);
      setBackground(Color.white);
      setSelectionBackground(Color.black);
      setSelectionForeground(Color.white);
    }

    protected void loadDefaultData() {
      Vector v = new Vector();
      File f = new File(".");
      File[] files = f.listFiles();
      for(int i = 0; i < files.length; i++) {
        FileElement fe = new FileElement();
        fe.setFile(files[i]);
        v.addElement(fe);
      }
      model.addData(v);
    }

    protected void createColumns() {
      for(int i = 0; i<model.cols.length; i++) {
        DefaultTableCellRenderer renderer = new FileRenderer();
        renderer.setHorizontalAlignment(model.cols[i].alignment);
        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
        setFont(new Font ("MicrosoftSanSerif", Font.PLAIN, 12));
        addColumn(column);
      }
    }
  }

  class SystemViewModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
      new ColumnDescriptor("Name", 40, JLabel.LEFT),
      new ColumnDescriptor("Size", 50, JLabel.LEFT),
    };
    protected Vector fileObjects;

    public SystemViewModel() {
      fileObjects = new Vector();
    }

    public void addData(Vector v) {
      fileObjects.removeAllElements();
      for(int i = 0; i<v.size(); i++) {
        fileObjects.addElement(v.elementAt(i));
      }
      updateObjects();
    }
    protected void updateObjects() {fireTableDataChanged();}
    public int getColumnCount() {return(cols.length);}
    public int getRowCount() {return(fileObjects.size());}
    public String getColumnName(int c) {return(cols[c].name);}

    public Object getValueAt(int row, int col) {
      if(getRowCount() <= 0)
        return "";
      if(row<0||row>=getRowCount())
        return "";
      Object o = fileObjects.elementAt(row);
      if(o instanceof FileElement) {
        FileElement fd = (FileElement) o;
        switch(col) {
          case 0: return fd.getName();
          case 1: return new Long(fd.getSize());
        }
      }
      return "";
    }

    class ColumnDescriptor {
      public String name;public int width;public int alignment;
      public ColumnDescriptor(String n, int w, int a) {name = n;width = w;alignment = a;}
    }
  }

  class FileUI {
    public ImageIcon icon = null;private String fileName;
    public FileUI(ImageIcon img, String fn) {icon = img;fileName = fn;}
    public String getFileName() {return(fileName);}
    public String toString() {return(fileName);}
  }

  public class FileElement {
    private File file;
    private long size;
    private FileUI name = null;

    public FileElement() {}

    public void setFile(File f) {
      ImageIcon icon = null;
      file = f;
      if(f.isDirectory())
        icon = new ImageIcon(FileSystemView.this.getClass().getResource("folder.gif"));
      else
        icon = new ImageIcon(FileSystemView.this.getClass().getResource("file.gif"));
      name = new FileUI(icon, f.getName());
      long size = f.length();
    }

    public long getSize() {return(size);}
    public FileUI getName() {return (name);}
    public boolean isDirectory() {return(file.isDirectory());}
  }

  public class FileRenderer extends DefaultTableCellRenderer {
    public void setValue(Object cell) {
      setFont(new Font ("MicrosoftSanSerif", Font.PLAIN, 12));
      if(cell instanceof FileUI) {
        FileUI fui = (FileUI)cell;
        setIcon(fui.icon);
        setText(fui.getFileName());
        setToolTipText(fui.getFileName());
      }
      else {
        super.setValue(cell);
        setToolTipText(cell.toString());
      }
    }
  }
  public static void main(String[] args) {FileSystemView t = new FileSystemView();}
}
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213113
all you have to do in adding dinamical data is to implement keyListener and mouseListener for your table and depending of where you do the action, update the filesVector from the model. I will try to write this code too in few minutes
0
 

Author Comment

by:thazim
ID: 6213128
i'm trying it out....
 i'll get back to U...Soon....
Thaz
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213146
all you have to do in adding dinamical data is to implement keyListener and mouseListener for your table and depending of where you do the action, update the filesVector from the model. I will try to write this code too in few minutes
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213158
Done again.
Notes :
- this example is supose to be runned in Windows systems (it loads as default directory 'c:'; to change that, take a look on the table constructor.)
- traversal of the directories is implemented only in one direction (root to leaf files/directories). For backward traversal you must include by hand in the Vector of listed files the '..' file.
- traversal is made by double clicking one 'directory' in the JTable.
- the listed files/directories are unsorted, strongly I believe that is your task.
- that's all (too much for 100 points but was nice to work with(for) you at this).

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class FileSystemView extends JFrame {
  private SystemView table;

  public FileSystemView() {
    getContentPane().setLayout(new BorderLayout());
    setSize(400, 300);
    setLocation(300, 100);
    table = new SystemView();
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    setVisible(true);
  }

  class SystemView extends JTable {
    SystemViewModel model;

    public SystemView() {
      model = new SystemViewModel();
      setAutoCreateColumnsFromModel(false);
      loadDirectory("c:");
      setModel(model);
      createColumns();
      setGridColor(Color.white);
      setForeground(Color.black);
      setBackground(Color.white);
      setSelectionBackground(Color.black);
      setSelectionForeground(Color.white);
      addMouseListener(new TableMouseAdapter(this, model));
    }

    protected void loadDirectory(String dir) {
      Vector v = new Vector();
      File f = new File(dir);
      File[] files = f.listFiles();
      for(int i = 0; i < files.length; i++) {
        FileElement fe = new FileElement();
        fe.setFile(files[i]);
        v.addElement(fe);
      }
      model.addData(v);
    }

    protected void loadDirectory(File f) {
      Vector v = new Vector();
      File[] files = f.listFiles();
      for(int i = 0; i < files.length; i++) {
        FileElement fe = new FileElement();
        fe.setFile(files[i]);
        v.addElement(fe);
      }
      model.addData(v);
    }

    protected void createColumns() {
      for(int i = 0; i<model.cols.length; i++) {
        DefaultTableCellRenderer renderer = new FileRenderer();
        renderer.setHorizontalAlignment(model.cols[i].alignment);
        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
        setFont(new Font ("MicrosoftSanSerif", Font.PLAIN, 12));
        addColumn(column);
      }
    }
  }

  class TableMouseAdapter extends MouseAdapter {
    SystemView table;
    SystemViewModel model;
    public TableMouseAdapter(SystemView t, SystemViewModel m){table = t;model = m;}
    public void mouseClicked(MouseEvent e) {// simple update the path
      if(e.getClickCount()==2) {//execute the LS (or the program in the next future)
        int row = table.getSelectedRow();
        File file = model.getFileAt(row);
        if(file.isDirectory())
          table.loadDirectory(file);
        return;
      }
    }
  }

  class SystemViewModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
      new ColumnDescriptor("Name", 40, JLabel.LEFT),
      new ColumnDescriptor("Size", 50, JLabel.LEFT),
    };
    protected Vector fileObjects;

    public SystemViewModel() {
      fileObjects = new Vector();
    }

    public void addData(Vector v) {
      fileObjects.removeAllElements();
      for(int i = 0; i<v.size(); i++) {
        fileObjects.addElement(v.elementAt(i));
      }
      updateObjects();
    }
    public File getFileAt(int row) {return(((FileElement)fileObjects.elementAt(row)).file);}
    protected void updateObjects() {fireTableDataChanged();}
    public int getColumnCount() {return(cols.length);}
    public int getRowCount() {return(fileObjects.size());}
    public String getColumnName(int c) {return(cols[c].name);}

    public Object getValueAt(int row, int col) {
      if(getRowCount() <= 0)
        return "";
      if(row<0||row>=getRowCount())
        return "";
      Object o = fileObjects.elementAt(row);
      if(o instanceof FileElement) {
        FileElement fd = (FileElement) o;
        switch(col) {
          case 0: return fd.getName();
          case 1: return new Long(fd.getSize());
        }
      }
      return "";
    }

    class ColumnDescriptor {
      public String name;public int width;public int alignment;
      public ColumnDescriptor(String n, int w, int a) {name = n;width = w;alignment = a;}
    }
  }

  class FileUI {
    public ImageIcon icon = null;private String fileName;
    public FileUI(ImageIcon img, String fn) {icon = img;fileName = fn;}
    public String getFileName() {return(fileName);}
    public String toString() {return(fileName);}
  }

  public class FileElement {
    private File file;
    private long size;
    private FileUI name = null;

    public FileElement() {}

    public void setFile(File f) {
      ImageIcon icon = null;
      file = f;
      if(f.isDirectory())
        icon = new ImageIcon(FileSystemView.this.getClass().getResource("folder.gif"));
      else
        icon = new ImageIcon(FileSystemView.this.getClass().getResource("file.gif"));
      name = new FileUI(icon, f.getName());
      long size = f.length();
    }

    public long getSize() {return(size);}
    public FileUI getName() {return (name);}
    public boolean isDirectory() {return(file.isDirectory());}
  }

  public class FileRenderer extends DefaultTableCellRenderer {
    public void setValue(Object cell) {
      setFont(new Font ("MicrosoftSanSerif", Font.PLAIN, 12));
      if(cell instanceof FileUI) {
        FileUI fui = (FileUI)cell;
        setIcon(fui.icon);
        setText(fui.getFileName());
        setToolTipText(fui.getFileName());
      }
      else {
        super.setValue(cell);
        setToolTipText(cell.toString());
      }
    }
  }
  public static void main(String[] args) {FileSystemView t = new FileSystemView();}
}
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213229
Done again.
Notes :
- this example is supose to be runned in Windows systems (it loads as default directory 'c:'; to change that, take a look on the table constructor.)
- traversal of the directories is implemented only in one direction (root to leaf files/directories). For backward traversal you must include by hand in the Vector of listed files the '..' file.
- traversal is made by double clicking one 'directory' in the JTable.
- the listed files/directories are unsorted, strongly I believe that is your task.
- that's all (too much for 100 points but was nice to work with(for) you at this).

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class FileSystemView extends JFrame {
  private SystemView table;

  public FileSystemView() {
    getContentPane().setLayout(new BorderLayout());
    setSize(400, 300);
    setLocation(300, 100);
    table = new SystemView();
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    setVisible(true);
  }

  class SystemView extends JTable {
    SystemViewModel model;

    public SystemView() {
      model = new SystemViewModel();
      setAutoCreateColumnsFromModel(false);
      loadDirectory("c:");
      setModel(model);
      createColumns();
      setGridColor(Color.white);
      setForeground(Color.black);
      setBackground(Color.white);
      setSelectionBackground(Color.black);
      setSelectionForeground(Color.white);
      addMouseListener(new TableMouseAdapter(this, model));
    }

    protected void loadDirectory(String dir) {
      Vector v = new Vector();
      File f = new File(dir);
      File[] files = f.listFiles();
      for(int i = 0; i < files.length; i++) {
        FileElement fe = new FileElement();
        fe.setFile(files[i]);
        v.addElement(fe);
      }
      model.addData(v);
    }

    protected void loadDirectory(File f) {
      Vector v = new Vector();
      File[] files = f.listFiles();
      for(int i = 0; i < files.length; i++) {
        FileElement fe = new FileElement();
        fe.setFile(files[i]);
        v.addElement(fe);
      }
      model.addData(v);
    }

    protected void createColumns() {
      for(int i = 0; i<model.cols.length; i++) {
        DefaultTableCellRenderer renderer = new FileRenderer();
        renderer.setHorizontalAlignment(model.cols[i].alignment);
        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
        setFont(new Font ("MicrosoftSanSerif", Font.PLAIN, 12));
        addColumn(column);
      }
    }
  }

  class TableMouseAdapter extends MouseAdapter {
    SystemView table;
    SystemViewModel model;
    public TableMouseAdapter(SystemView t, SystemViewModel m){table = t;model = m;}
    public void mouseClicked(MouseEvent e) {// simple update the path
      if(e.getClickCount()==2) {//execute the LS (or the program in the next future)
        int row = table.getSelectedRow();
        File file = model.getFileAt(row);
        if(file.isDirectory())
          table.loadDirectory(file);
        return;
      }
    }
  }

  class SystemViewModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
      new ColumnDescriptor("Name", 40, JLabel.LEFT),
      new ColumnDescriptor("Size", 50, JLabel.LEFT),
    };
    protected Vector fileObjects;

    public SystemViewModel() {
      fileObjects = new Vector();
    }

    public void addData(Vector v) {
      fileObjects.removeAllElements();
      for(int i = 0; i<v.size(); i++) {
        fileObjects.addElement(v.elementAt(i));
      }
      updateObjects();
    }
    public File getFileAt(int row) {return(((FileElement)fileObjects.elementAt(row)).file);}
    protected void updateObjects() {fireTableDataChanged();}
    public int getColumnCount() {return(cols.length);}
    public int getRowCount() {return(fileObjects.size());}
    public String getColumnName(int c) {return(cols[c].name);}

    public Object getValueAt(int row, int col) {
      if(getRowCount() <= 0)
        return "";
      if(row<0||row>=getRowCount())
        return "";
      Object o = fileObjects.elementAt(row);
      if(o instanceof FileElement) {
        FileElement fd = (FileElement) o;
        switch(col) {
          case 0: return fd.getName();
          case 1: return new Long(fd.getSize());
        }
      }
      return "";
    }

    class ColumnDescriptor {
      public String name;public int width;public int alignment;
      public ColumnDescriptor(String n, int w, int a) {name = n;width = w;alignment = a;}
    }
  }

  class FileUI {
    public ImageIcon icon = null;private String fileName;
    public FileUI(ImageIcon img, String fn) {icon = img;fileName = fn;}
    public String getFileName() {return(fileName);}
    public String toString() {return(fileName);}
  }

  public class FileElement {
    private File file;
    private long size;
    private FileUI name = null;

    public FileElement() {}

    public void setFile(File f) {
      ImageIcon icon = null;
      file = f;
      if(f.isDirectory())
        icon = new ImageIcon(FileSystemView.this.getClass().getResource("folder.gif"));
      else
        icon = new ImageIcon(FileSystemView.this.getClass().getResource("file.gif"));
      name = new FileUI(icon, f.getName());
      long size = f.length();
    }

    public long getSize() {return(size);}
    public FileUI getName() {return (name);}
    public boolean isDirectory() {return(file.isDirectory());}
  }

  public class FileRenderer extends DefaultTableCellRenderer {
    public void setValue(Object cell) {
      setFont(new Font ("MicrosoftSanSerif", Font.PLAIN, 12));
      if(cell instanceof FileUI) {
        FileUI fui = (FileUI)cell;
        setIcon(fui.icon);
        setText(fui.getFileName());
        setToolTipText(fui.getFileName());
      }
      else {
        super.setValue(cell);
        setToolTipText(cell.toString());
      }
    }
  }
  public static void main(String[] args) {FileSystemView t = new FileSystemView();}
}
0
 

Author Comment

by:thazim
ID: 6213266
halo...
  i'm getting run time error...for this program...

the error is..
Exception in thread "main" java.lang.NullPoiterException

   at javax.swing.ImageIcon.<init>(ImageIcon.java:IOS)
etc..

what to Do????
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213336
This means you don't hae he folder.gif and file.gif files into your working directory.
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213345
I told you early that you must have this two image files into the same directory as the compiled code is. Supose your class files are in c:\Java\Tests then in the same directory you must these two images. At me is working fine.
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213353
... so ?
0
 

Author Comment

by:thazim
ID: 6213647
yes.....I got it atlast.....
  thankx for Ur timely Help....:-)
Thaz
 
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6213772
I will remember ...
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
servlet  URL Rewriting 1 42
Oracle SQL syntax check  without executing 6 74
java example issue 3 19
restrict decimal places for double datatype 10 19
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
The viewer will learn how to implement Singleton Design Pattern in Java.

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question