java - DefaultTableModel 的 ImageIcon

标签 java swing imageicon defaulttablemodel

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

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 类

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"));

}

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

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

它实际上显示的是图标而不是来源?

最佳答案

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

参见 Editors and Renderers 如何使用表格教程的一部分。

关于java - DefaultTableModel 的 ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14005782/

相关文章:

java - 使用 JavaMail 解析文本/html 数据

java - 如何在 Android 应用程序中创建类似 gmail 撰写的东西

java - 将 Selenium WebDriver 与 Tor 一起使用

java - Jframe图像+文本字段

java - 在java中切换imageIcon?

java - 3.13 版中缺少 Apache POI hslf?

java - 使用从 Json 响应传递的对象填充 JTable

java - ActionListener 上未找到符号错误

java - 如何获取 String Java Jtable 中的 ImageIcon 路径