复制的DefaultTableModel数据到剪贴板(Copying DefaultTableMod

2019-07-21 03:59发布

我有未来的JTable

private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(null);

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"Hat", "New York", "1000"},
            {"T-Shirt", "New York", "3500"},
            {"Sweater", "Washington", "2800"},
            {"Bag", "California", "7000"},
        },
        new String [] {
            "Name", "Warehouse", "Quantity"
        }
    ));
    jScrollPane1.setViewportView(jTable1);

    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(19, 11, 375, 170);

    jButton1.setText("Copy");
    getContentPane().add(jButton1);
    jButton1.setBounds(113, 195, 63, 23);

    jButton2.setText("Exit");
    getContentPane().add(jButton2);
    jButton2.setBounds(225, 195, 53, 23);

    pack();
}

我想按钮复制模式到剪贴板的信息,但它不工作,我已经尝试使用

String myString = "This text will be copied into clipboard when running this code!";
StringSelection stringSelection = new StringSelection (myString);
Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);

Answer 1:

这个概念比较简单,实施更复杂一点。

关键是要找到各种应用将承认并允许你转换你的数据的MIME类型。

我不包括CSV翻译,它不会花费太多来获取从示例代码的工作,另外,我还没有包括在任何表格单元格值“格式化”,我相信你能明白这出来为好。

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class CopyTableModel {

    public static void main(String[] args) {
        DefaultTableModel model = new DefaultTableModel(
                new Object[][]{
            {"A1", "A2", "A3", "A4", "A5"},
            {"B1", "B2", "B3", "B4", "B5"},
            {"C1", "C2", "C3", "C4", "C5"},
            {"D1", "D2", "D3", "D4", "D5"},
            {"E1", "E2", "E3", "E4", "E5"},
            {"F1", "F2", "F3", "F4", "F5"}
        },
                new Object[]{"1", "2", "3", "4", "5"});

        Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
        cb.setContents(new TableTransferable(model), new ClipboardOwner() {
            @Override
            public void lostOwnership(Clipboard clipboard, Transferable contents) {
                System.out.println("You lose :(");
            }
        });

    }

    public static class TableTransferable implements Transferable {

        public static final DataFlavor TABLE_DATA_FLAVOR = new DataFlavor(TableModel.class, "binary/x-java-tablemodel; class=<javax.swing.TableModel>");
        public static final DataFlavor HTML_DATA_FLAVOR = new DataFlavor("text/html", "HTML");
        public static final DataFlavor CSV_DATA_FLAVOR = new DataFlavor("text/csv", "CVS");
        public static final DataFlavor PLAIN_DATA_FLAVOR = new DataFlavor("text/plain", "Plain text");
        public static final DataFlavor SERIALIZED_DATA_FLAVOR = new DataFlavor(String.class, "application/x-java-serialized-object; Plain text");
        private final TableModel model;

        public TableTransferable(TableModel model) {
            this.model = model;
        }

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{TABLE_DATA_FLAVOR, HTML_DATA_FLAVOR, CSV_DATA_FLAVOR, SERIALIZED_DATA_FLAVOR};
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            System.out.println("isSupported " + flavor);
            boolean supported = false;
            for (DataFlavor mine : getTransferDataFlavors()) {
                if (mine.equals(flavor)) {
                    supported = true;
                    break;
                }
            }
            return supported;
        }

        @Override
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            System.out.println("get " + flavor);
            Object data = null;
            if (TABLE_DATA_FLAVOR.equals(flavor)) {
                data = model;
            } else if (HTML_DATA_FLAVOR.equals(flavor)) {
                data = new ByteArrayInputStream(formatAsHTML().getBytes());
            } else if (SERIALIZED_DATA_FLAVOR.equals(flavor)) {
                data = formatAsHTML();
            } else if (CSV_DATA_FLAVOR.equals(flavor)) {
                data = new ByteArrayInputStream("CSV".getBytes());
            } else {
                throw new UnsupportedFlavorException(flavor);
            }
            return data;
        }

        public String formatAsHTML() {
            StringBuilder sb = new StringBuilder(128);
            sb.append("<html><body>");
            sb.append("<table>");
            sb.append("<tr>");
            for (int index = 0; index < model.getColumnCount(); index++) {
                sb.append("<th>").append(model.getColumnName(index)).append("</th>");
            }
            sb.append("</tr>");
            for (int rowIndex = 0; rowIndex < model.getRowCount(); rowIndex++) {
                sb.append("<tr>");
                for (int colIndex = 0; colIndex < model.getColumnCount(); colIndex++) {
                    Object o = model.getValueAt(rowIndex, colIndex);
                    // You will want to format the value...
                    String value = o == null ? "" : o.toString();
                    sb.append("<td>").append(value).append("</td>");
                }
                sb.append("</tr>");
            }
            sb.append("</table>");

            return sb.toString();
        }
    }
}


Answer 2:

JTable中的默认复制功能将复制选定的数据行到剪贴板。

见行动地图行动的一个方法,让您可以访问此动作。 使用提供的类的代码如下:

Action copyAction = new ActionMapAction("Copy Table", table, "copy");
JButton copyButton = new JButton(copyAction);


文章来源: Copying DefaultTableModel data to clipboard