1

我正在为学校制作一个程序,您可以记录系统剪贴板历史记录,我的老师说到目前为止还不错,但我需要添加图像。所以我得到了一些图像来表示图像、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() });

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

4

1 回答 1

4

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

请参阅如何使用表格教程的编辑器和渲染器部分。

于 2012-12-22T19:30:21.750 回答