javalearner
javalearner

Reputation: 103

Image display in JTable cell

I use the following program for creating JTable using java class. If I get the images for warnIcon,infoIcon from optionpane it displays properly. However, if I add image from my system it doesn't display in table. A blank space is displayed instead of my image. How can I draw an image from file (e.g. A.jpg) in that table?

package pointer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.plaf.OptionPaneUI;
import javax.swing.table.*;
import sun.swing.ImageIconUIResource;

public class TableIcon1 extends JFrame  {
    private JTable table;
    private int pHeight = 60;
       public TableIcon1() {
           ImageIcon testIcon = new ImageIcon("A.jpg");
          // ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
           ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
           ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
           String[] columnNames = {"Picture", "Description"};
           Object[][] data = {{testIcon  , "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
           DefaultTableModel model = new DefaultTableModel(data, columnNames);
           table = new JTable(model) {
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(2, column).getClass();
            }
          };
           table.setRowHeight(pHeight);
           table.setPreferredScrollableViewportSize(table.getPreferredSize());
           JScrollPane scrollPane = new JScrollPane(table);
           add(scrollPane, BorderLayout.CENTER);
         }

    public static void main(String[] args) {
        TableIcon1 frame = new TableIcon1();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocation(150, 150);
        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 2

Views: 4698

Answers (1)

mKorbel
mKorbel

Reputation: 109813

ImageIcon testIcon = new ImageIcon("A.jpg"); is road to nowhere

Icon is common that never returns any exceptions for wrong path or null value, you have to test fro that

best of way would be create a new folder with name icons in your Java project and there copy your A.jpg Icon

then you can only call

URL url = ClassLoader.getSystemClassLoader().getResource("icons/A.jpg");
ImageIcon testIcon = new ImageIcon(url);

Upvotes: 3

Related Questions