如何将jtable的内容复制到剪贴板

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将jtable的内容复制到剪贴板相关的知识,希望对你有一定的参考价值。

我有jtable提交数据。我想为Jbutton的Action创建java代码。我的要求是当我点击按钮,然后将jtable的所有内容复制到剪贴板。我怎样才能做到这一点。

    String[] columnNames={"DATE","Steet"};
    String[][] cells=new String[ar.size()][2];
    for(int i=0;i<ar.size();i++){
        cells[i][0]=((PRIvariable)ar.get(i)).incDate;
        cells[i][1]=((PRIvariable)ar.get(i)).selectedSteer;
    }
    table = new JTable(cells,columnNames);
    table.setVisible(true);
    table.setSize(400, 400);
    js=new JScrollPane();
    js.setViewportView(table);
    js.setBounds(10, 230,500, 215);
    js.setVisible(true);
    add(js,java.awt.BorderLayout.CENTER);
  • 在这段代码中ar是我的arraylist。
  • 我怎么能写代码女巫可以复制这个Jtable的内容。
答案

当我在过去需要这样做时,我开始使用这里的代码:http://www.javaworld.com/javatips/jw-javatip77.html

并进行了修改以创建按钮的操作,该按钮可将数据和列标题从表复制到剪贴板。

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.StringTokenizer;




/**
 * ExcelAdapter enables Copy-Paste Clipboard functionality on JTables. The clipboard data format used by the adapter is
 * compatible with the clipboard format used by Excel. This provides for clipboard interoperability between enabled
 * JTables and Excel.
 */
public class ExcelAdapter implements ActionListener {


    private String rowstring, value;
    private Clipboard clipboard;
    private StringSelection stsel;
    private JTable jTable1;


    /**
     * The Excel Adapter is constructed with a JTable on which it enables Copy-Paste and acts as a Clipboard listener.
     */
    public ExcelAdapter(JTable myJTable) {

        jTable1 = myJTable;
        final KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK, false);
        // Identifying the copy KeyStroke user can modify this
        // to copy on some other Key combination.
        final KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK, false);
        // Identifying the Paste KeyStroke user can modify this
        //to copy on some other Key combination.
        jTable1.registerKeyboardAction(this, "Copy", copy, JComponent.WHEN_FOCUSED);
        jTable1.registerKeyboardAction(this, "Paste", paste, JComponent.WHEN_FOCUSED);
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    }


    /**
     * Public Accessor methods for the Table on which this adapter acts.
     */
    public JTable getJTable() {

        return jTable1;
    }


    public void setJTable(JTable jTable1) {

        this.jTable1 = jTable1;
    }


    /**
     * This method is activated on the Keystrokes we are listening to in this implementation. Here it listens for Copy
     * and Paste ActionCommands. Selections comprising non-adjacent cells result in invalid selection and then copy
     * action cannot be performed. Paste is done by aligning the upper left corner of the selection with the 1st element
     * in the current selection of the JTable.
     */
    @Override
    public void actionPerformed(ActionEvent e) {

        final String actionCommand = e.getActionCommand();

        if (actionCommand.equals("Copy")) {

            StringBuilder sbf = new StringBuilder();
            // Check to ensure we have selected only a contiguous block of cells.
            final int numcols = jTable1.getSelectedColumnCount();
            final int numrows = jTable1.getSelectedRowCount();
            final int[] rowsselected = jTable1.getSelectedRows();
            final int[] colsselected = jTable1.getSelectedColumns();

            if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] &&
                    numrows == rowsselected.length) &&
                    (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] &&
                            numcols == colsselected.length))) {
                JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
                                              "Invalid Copy Selection",
                                              JOptionPane.ERROR_MESSAGE);
                return;
            }
            for (int i = 0; i < numrows; i++) {
                for (int j = 0; j < numcols; j++) {
                    sbf.append(jTable1.getValueAt(rowsselected[i], colsselected[j]));
                    if (j < numcols - 1) {
                        sbf.append('	');
                    }
                }
                sbf.append('
');
            }
            stsel = new StringSelection(sbf.toString());
            clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stsel, stsel);

        } else if (actionCommand.equals("Paste")) {

            System.out.println("Trying to Paste");
            final int startRow = (jTable1.getSelectedRows())[0];
            final int startCol = (jTable1.getSelectedColumns())[0];
            try {
                final String trString = (String) (clipboard.getContents(this).getTransferData(DataFlavor.stringFlavor));
                System.out.println("String is:" + trString);
                final StringTokenizer st1 = new StringTokenizer(trString, "
");
                for (int i = 0; st1.hasMoreTokens(); i++) {
                    rowstring = st1.nextToken();
                    StringTokenizer st2 = new StringTokenizer(rowstring, "	");
                    for (int j = 0; st2.hasMoreTokens(); j++) {
                        value = (String) st2.nextToken();
                        if (startRow + i < jTable1.getRowCount() &&
                                startCol + j < jTable1.getColumnCount()) {
                            jTable1.setValueAt(value, startRow + i, startCol + j);
                        }
                        System.out.println("Putting " + value + "at row = " + startRow + i + " column = " + startCol + j);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

    }

}
另一答案

JTable已经支持复制Action。 Action Map Action展示了如何使用JButton轻松使用此Action,因此您无需重写代码。

另一答案

这是来自javaworld(1999年)的ExcelAdapter的更新版本。 Link

用来:

jTable1.addKeyListener(new ClipboardKeyAdapter(jTable1));

clipboard key adapter.Java

        public class ClipboardKeyAdapter extends KeyAdapter {

        private static final String LINE_BREAK = "
"; 
        private static final String CELL_BREAK = "	"; 
        private static final Clipboard CLIPBOARD = Toolkit.getDefaultToolkit().getSystemClipboard(); 

        private final JTable table; 

        public ClipboardKeyAdapter(JTable table) { 
                this.table = table; 
        } 

        @Override 
        public void keyReleased(KeyEvent event) { 
                if (event.isControlDown()) { 
                        if (event.getKeyCode()==KeyEvent.VK_C) { // Copy                        
                                cancelEditing(); 
                                copyToClipboard(false); 
                        } else if (event.getKeyCode()==KeyEvent.VK_X) { // Cut 
                                cancelEditing(); 
                                copyToClipboard(true); 
                        } else if (event.getKeyCode()==KeyEvent.VK_V) { // Paste 
                                cancelEditing(); 
                                pasteFromClipboard();           
                        } 
                } 
        } 

        private void copyToClipboard(boolean isCut) { 
                int numCols=table.getSelectedColumnCount(); 
                int numRows=table.getSelectedRowCount(); 
                int[] rowsSelected=table.getSelectedRows(); 
                int[] colsSelected=table.getSelectedColumns(); 
                if (numRows!=rowsSelected[rowsSelected.length-1]-rowsSelected[0]+1 || numRows!=rowsSelected.length || 
                                numCols!=colsSelected[colsSelected.length-1]-colsSelected[0]+1 || numCols!=colsSelected.length) {

    

以上是关于如何将jtable的内容复制到剪贴板的主要内容,如果未能解决你的问题,请参考以下文章

如何自动选定一个网页显示的全部内容到复制到剪贴板中?

如何将过滤后的 jTable 的内容导出到 pdfpTable

如何获取文本文件的内容并将其复制到剪贴板?

如何将字符串的内容复制到 C# 中的剪贴板? [复制]

如何将字符串的内容复制到 C# 中的剪贴板? [复制]

autoit中如何把指定内容复制到剪贴板?