用于DefaultTableModel的ImageIcon [英] ImageIcon for DefaultTableModel

查看:79
本文介绍了用于DefaultTableModel的ImageIcon的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为学校编写一个程序,您可以记录系统剪贴板的历史记录,我的老师说到目前为止还不错,但是我需要添加图像.因此,我得到了一些图像来表示图像,URL,文本或文件夹.但是,当我尝试对图像添加.addRow时,它将显示图像的来源,而不是实际的图像.这是我的课程

I'm making a program for school which you can log the systems clipboard history, my teacher said it's good so far, but I need to add images. So I got a few images to represent an image, url, text, or a folder. But when I try to .addRow with the image, it shows the source of the image and not the actual image. Here's my class

public class Main extends JFrame implements ClipboardOwner {

    private static final long serialVersionUID = -7215911935339264676L;

    public final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    private static DecimalFormat df = new DecimalFormat("#.##");

    public static ArrayList<NewEntry> history = new ArrayList<NewEntry>();

    private DefaultTableModel model;

    private JTable table;

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(new GraphiteLookAndFeel());
        Static.main.setVisible(true);
    }

    public Main() {
        super("Clipboard Logger");

        setSize(667, 418);
        setLocationRelativeTo(null);
        getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        model = new DefaultTableModel(null, new String[] { "Type", "Content", "Size", "Date" });
        table = new JTable(model) {

            private static final long serialVersionUID = 2485117672771964339L;

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int r = table.rowAtPoint(e.getPoint());
                if (r >= 0 && r < table.getRowCount()) {
                    table.setRowSelectionInterval(r, r);
                } else {
                    table.clearSelection();
                }

                int rowindex = table.getSelectedRow();
                if (rowindex < 0)
                    return;
                if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) {
                    createAndShowPopupMenu(rowindex, e.getX(), e.getY());
                }
            }
        });

        JScrollPane pane = new JScrollPane(table);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

        getContentPane().add(pane);

        Transferable trans = clipboard.getContents(this);
        regainOwnership(trans);

        setIconImage(Static.icon);
    }

    @Override
    public void lostOwnership(Clipboard clipboard, Transferable transferable) {
        try {
            Thread.sleep(50);
            Transferable contents = clipboard.getContents(this);
            processContents(contents);
            regainOwnership(contents);
        } catch (Exception e) {
            regainOwnership(clipboard.getContents(this));
        }
    }

    public void processContents(Transferable t) throws UnsupportedFlavorException, IOException {
        System.out.println("Processing: " + t);
        DataFlavor[] flavors = t.getTransferDataFlavors();
        File file = new File(t.getTransferData(flavors[0]).toString().replace("[", "").replace("]", ""));
        System.out.println("HI"+file.getName());
        NewEntry entry = null;
        if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            System.out.println("String Flavor");
            String s = (String) (t.getTransferData(DataFlavor.stringFlavor));
            entry = new NewEntry(EntryType.TEXT, s, getSizeUnit(s.getBytes().length), DateFormat.getDateInstance().format(new Date()));
        } else if (isValidImage(file.getName()) && file.exists()) {
            System.out.println("Image Flavor");

            entry = new NewEntry(EntryType.IMAGE, file.getAbsolutePath(), getSizeUnit(file.length()), DateFormat.getDateInstance().format(new Date()));
        }
        history.add(entry);
        model.addRow(new Object[] { entry.getIcon(), entry.getContent(), entry.getSize(), entry.getDate() });
    }

    public void regainOwnership(Transferable t) {
        clipboard.setContents(t, this);
    }

    public boolean isValidImage(String filename) {
        for (String string : ImageIO.getReaderFormatNames()) {
            if (filename.endsWith(string)) {
                return true;
            }
        }
        return false;
    }

    public void createAndShowPopupMenu(int index, int x, int y) {
        final NewEntry entry = history.get(index);
        if (entry == null) return;
        JPopupMenu pop = new JPopupMenu();
        JMenu jm = new JMenu("Open in");
        JMenuItem jmi = new JMenuItem("Browser");
        jmi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    Desktop.getDesktop().browse(new URI("file:///"+entry.getContent().replace("\\", "/")));
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        jm.add(jmi);
        jmi = new JMenuItem("Windows Explorer");
        jmi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    Desktop.getDesktop().open(new File(entry.getContent()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        jm.add(jmi);
        pop.add(jm);
        pop.show(this, x, y);
    }

    public static String getSizeUnit(long dataSize) {
        double n = dataSize;
        String suffix = "B";
        if (n > 1000) {
            suffix = "KB";
            n /= 1000;
        }
        if (n > 1000) {
            suffix = "MB";
            n /= 1000;
        }
        if (n > 1000) {
            suffix = "GB";
            n /= 1000;
        }
        return df.format(n)+suffix;
    }
}

这是我的EntryType类

And here's my EntryType class

public class EntryType {

public static final ImageIcon TEXT = new ImageIcon(Toolkit.getDefaultToolkit().getImage("./resources/text.png"));

public static final ImageIcon URL = new ImageIcon(Toolkit.getDefaultToolkit().getImage("./resources/url.png"));

public static final ImageIcon FILE = new ImageIcon(Toolkit.getDefaultToolkit().getImage("./resources/file.png"));

public static final ImageIcon IMAGE = new ImageIcon(Toolkit.getDefaultToolkit().getImage("./resources/image.png"));

}

当执行以下代码行时,我将如何做到这一点:

How would I make it so when I do this line of code:

model.addRow(new Object [] {entry.getIcon(),entry.getContent(),entry.getSize(),entry.getDate()});

model.addRow(new Object[] { entry.getIcon(), entry.getContent(), entry.getSize(), entry.getDate() });

它实际上显示图标而不是源代码吗?

it actually shows the icon and not the source?

推荐答案

JTable提供图像的渲染器.覆盖getColumnClass()并为具有图标的列返回Icon.class.

JTable provides a renderer for images. Override getColumnClass() and return Icon.class for the column that has an icon.

请参见编辑器和渲染器部分>如何使用表格教程.

See Editors and Renderers part of How to Use Tables tutorial.

这篇关于用于DefaultTableModel的ImageIcon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆