Solved

Icon

Posted on 2001-06-20
15
388 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
Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
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

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Python Assistance 7 80
netstat -ano | find "8000" and taskkill /f /pid 2984 3 56
tomcat startup error 5 63
hibernate jars 4 30
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

770 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