1

I try to insert my image from database to JTable but, it can't be shown. How can i overcome this problem?

public void loadData(ArrayList<Monster> monsters) {
    /**
     * Collection of Cell Example : Gondar 45 56 78 4 Axe 34 67 90 5
     */
    Vector<Vector<String>> data = new Vector<Vector<String>>();
    for (Monster item : monsters) {
        Vector<String> dataRow = new Vector<String>();
        dataRow.add("" + new ImageIcon(getClass().getResource("/images/monster/"+item.getAvatarUrl())));
        dataRow.add("" + item.getName());
        dataRow.add("" + item.getHp());
        dataRow.add("" + item.getDp());
        dataRow.add("" + item.getAp());
        dataRow.add("" + item.getLevel());
        data.add(dataRow);
    }
    this.setDataVector(data, columnElement);
}
1
  • 1
    for better help sooner post an SSCCE/MCVE, short, runnable, compilable with hardcoded value for JTable/XxxTableModel in local variable (instead of JDBC) take Icon from UIManager - UIManager.getIcon("OptionPane.errorIcon") Commented Dec 18, 2014 at 8:41

1 Answer 1

1

1) Seems you get Icon's from classpath not db. 2) You need to add ImageIcon into TableModel, but you add String instead of that.

You can override getColumnClass method of your TableModel to return Icon.class for proper column and store ImageIcon in that column. For example:

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class TestFrame extends JFrame {

    public static void main(String... s){
        new TestFrame();
    }

    public TestFrame() {
        init();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void init() {
        DefaultTableModel model = new DefaultTableModel(0,3){
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if(columnIndex == 1){
                    return Icon.class;
                }
                return super.getColumnClass(columnIndex);
            }
        };
        ImageIcon icon = new ImageIcon(TestFrame.class.getResource("1.png"));
        model.addRow(new Object[]{"1",icon,"2"});

        JTable t = new JTable(model);
        add(new JScrollPane(t));
    }

}

Here is 1 row in TableModel in second column stored ImageIcon, and JTable knows how to display it with column class Icon.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.