Link to home
Start Free TrialLog in
Avatar of thazim
thazim

asked on

Icon

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
Avatar of Ovi
Ovi

I will make you the code ... in short time.
Avatar of thazim

ASKER

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;
}
}
Is coming
ASKER CERTIFIED SOLUTION
Avatar of Ovi
Ovi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of thazim

ASKER

i'm trying it out....
 i'll get back to U...Soon....
Thaz
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
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();}
}
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();}
}
Avatar of thazim

ASKER

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????
This means you don't hae he folder.gif and file.gif files into your working directory.
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.
... so ?
Avatar of thazim

ASKER

yes.....I got it atlast.....
  thankx for Ur timely Help....:-)
Thaz
 
I will remember ...