سؤال

I am newbie on java-swing. I am trying to add icon in table cell. but when i add ImageIcon in cell then it's showing only path instead of icon.

Here is my code.

 public void createGUI(ArrayList<String> params, String type) {

    try {
        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("ParameterName");
        model.addColumn("ParameterType");
        model.addColumn("Operation");
        for (int i = 0; i < params.size() - 4; i++) {
            String param_name = params.get(i).toString().substring(0, params.get(i).toString().indexOf("["));
            String param_type = params.get(i).toString().substring(params.get(i).toString().indexOf("[") + 1, params.get(i).toString().indexOf("]"));
            //URL url = ClassLoader.getSystemClassLoader().getResource("");
            ImageIcon image = new ImageIcon("/com/soastreamer/resources/delete_idle.png");
          //  JLabel label = new JLabel(image);
            model.addRow(new Object[]{param_name, param_type.toUpperCase(),image});

        }


        Action delete = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                JTable table = (JTable) e.getSource();
                int modelRow = Integer.valueOf(e.getActionCommand());
                ((DefaultTableModel) table.getModel()).removeRow(modelRow);
            }
        };

Here is image for clear understanding.

enter image description here

Please give me hint or any reference. Thank you.

هل كانت مفيدة؟

المحلول

The problem lies with your TableModel, you have to tell the table that it has to render an image in that column overriding the getColumnClass(int column) method of the model.

Look at this answer by camickr.

UPDATE

Minimal example of a JTable with an ImageIcon using DefaultTableModel's renderer to paint it. I borrowed the updateRowHeights() code from this answer again by camickr, without it the icon was bigger than the row and wasn't fully displayed.

The important thing here is that now when the renderer calls getColumnClass(1), it gets ImageIcon.class so the code to render icons will be executed. By default this method would return Object.class and the renderer would ignore the fact that it's an icon.

import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class ImageIconTable
{
    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ImageIconTable().initGUI();
            }
        });
    }

    public void initGUI()
    {
        JFrame frame = new JFrame();        
        DefaultTableModel tableModel = new DefaultTableModel()
        {
            @Override
            public Class getColumnClass(int column)
            {
                if (column == 1) return ImageIcon.class; 
                return Object.class;
            }
        };
        tableModel.addColumn("Row 1");
        tableModel.addColumn("Icons Row");
        tableModel.addRow(new Object[]{"This cell is an Object", new ImageIcon("icon.jpg")});
        _table = new JTable(tableModel);

        updateRowHeights();

        frame.add(new JScrollPane(_table), BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private void updateRowHeights()
    {
        try
        {
            for (int row = 0; row < _table.getRowCount(); row++)
            {
                int rowHeight = _table.getRowHeight();

                for (int column = 0; column < _table.getColumnCount(); column++)
                {
                    Component comp = _table.prepareRenderer(_table.getCellRenderer(row, column), row, column);
                    rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
                }
                _table.setRowHeight(row, rowHeight);
            }
        }
        catch(ClassCastException e) {}
    }

    private JTable _table;
}

It looks like this:

Table displaying an icon

نصائح أخرى

First, I suggest you to use ImageIo.read() and use the BufferedImage returned as argument for your ImageIcon object. Second, use the Class.getResource() facility

YourClass.class.getResource("/com/soastreamer/resources/delete_idle.png");

Then, everything should work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top