当前位置: 首页 > 面试题库 >

使用剪贴板和AbstractAction复制和粘贴JTable

上官彬
2023-03-14
问题内容

当我尝试使用粘贴到JTable单元格时table.setValueAt(),我要粘贴的单元格保持空白,但setValueAt()似乎可以正常工作。另外,当我尝试从一个单元格剪切或复制JPopupMenu时,如果要粘贴到另一个单元格,则我的“粘贴”选项将保持禁用状态。我不知道为什么。我的代码如下。

class CopyAction extends AbstractAction {

    private JTable table;

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

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        int row = table.getSelectedRow();
        int col = table.getSelectedColumn();

        Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
        cb.setContents(new CellTransferable(table.getValueAt(row, col)), null);

    }

}

class CutAction extends AbstractAction {

    private JTable table;

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

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        int row = table.getSelectedRow();
        int col = table.getSelectedColumn();

        Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
        cb.setContents(new CellTransferable(table.getValueAt(row, col)), null);



    }

}

class PasteAction extends AbstractAction {

    private JTable table;
    private GridModel gridModel;

    public PasteAction(JTable tbl, GridModel gm) 
    {
        gridModel = gm;

        table = tbl;

        final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();

        cb.addFlavorListener(new FlavorListener() {
            @Override
            public void flavorsChanged(FlavorEvent e) 
            { 
                setEnabled(cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR));
            }
        });
        setEnabled(cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR));
    }

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        int row = table.getSelectedRow();
        int col = table.getSelectedColumn();

        Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
        if (cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR)) 
        {
            try 
            {
                Object value = cb.getData(CellTransferable.CELL_DATA_FLAVOR);
                System.out.println(value);
                table.setValueAt(value, row, col);


            } 
            catch (UnsupportedFlavorException | IOException ex) 
            {
                ex.printStackTrace();
            }
        }
    }

}

class CellTransferable implements Transferable {

    public static final DataFlavor CELL_DATA_FLAVOR = new DataFlavor(Object.class, "application/x-cell-value");

    private Object cellValue;

    public CellTransferable(Object cellValue) {
        this.cellValue = cellValue;
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[]{CELL_DATA_FLAVOR};
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return CELL_DATA_FLAVOR.equals(flavor);
    }

    @Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (!isDataFlavorSupported(flavor)) {
            throw new UnsupportedFlavorException(flavor);
        }
        return cellValue;
    }


}

Here’s my code for setValueAt()

class MyModel extends AbstractTableModel  
{
    private String[] names = {"1", "2", "3", "4", "5" };    
    private String[][] values = new String[5][5];

    //...other methods

    public void setValueAt(Object value, int row, int col) 
    {
        if (value instanceof Double || value instanceof Integer)
            values[row][col] = value.toString();
        else
        {
            values[row][col] = (String) value;
        }

        fireTableCellUpdated(row, col);
    }

}

问题答案:

根据您的示例代码,并且必须填写空白,它对
我有用…

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class TableExample {

    public static void main(String[] args) {
        new TableExample();
    }

    public TableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTable table = new JTable(new MyModel());
                final JPopupMenu pm = new JPopupMenu();
                pm.add(new CopyAction(table));
                pm.add(new PasteAction(table));

                table.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (e.isPopupTrigger()) {
                            highlightRow(e);
                            doPopup(e);
                        }
                    }

                    @Override
                    public void mouseReleased(MouseEvent e) {
                        if (e.isPopupTrigger()) {
                            highlightRow(e);
                            doPopup(e);
                        }
                    }

                    protected void doPopup(MouseEvent e) {
                        pm.show(e.getComponent(), e.getX(), e.getY());
                    }

                    protected void highlightRow(MouseEvent e) {
                        JTable table = (JTable) e.getSource();
                        Point point = e.getPoint();
                        int row = table.rowAtPoint(point);
                        int col = table.columnAtPoint(point);

                        table.setRowSelectionInterval(row, row);
                        table.setColumnSelectionInterval(col, col);
                    }

                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(table);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

            }
        });
    }

    public class MyModel extends AbstractTableModel {

        private String[] names = {"1", "2", "3", "4", "5"};
        private String[][] values = new String[5][5];

        public MyModel() {
            values = new String[10][names.length];
            for (int row = 0; row < 10; row++) {
                for (int col = 0; col < names.length; col++) {
                    values[row][col] = String.valueOf((char) ((row * names.length) + col + 65));
                }
            }
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            if (value instanceof Double || value instanceof Integer) {
                values[row][col] = value.toString();
            } else {
                values[row][col] = (String) value;
            }

            fireTableCellUpdated(row, col);
        }

        @Override
        public int getRowCount() {
            return values.length;
        }

        @Override
        public int getColumnCount() {
            return names.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return values[rowIndex][columnIndex];
        }

    }

    class CopyAction extends AbstractAction {

        private JTable table;

        public CopyAction(JTable table) {
            this.table = table;
            putValue(NAME, "Copy");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            int col = table.getSelectedColumn();

            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
            cb.setContents(new CellTransferable(table.getValueAt(row, col)), null);

        }

    }

    class CutAction extends AbstractAction {

        private JTable table;

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

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            int col = table.getSelectedColumn();

            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
            cb.setContents(new CellTransferable(table.getValueAt(row, col)), null);

        }

    }

    class PasteAction extends AbstractAction {

        private JTable table;

        public PasteAction(JTable tbl) {

            putValue(NAME, "Paste");

            table = tbl;

            final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();

            cb.addFlavorListener(new FlavorListener() {
                @Override
                public void flavorsChanged(FlavorEvent e) {
                    setEnabled(cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR));
                }
            });
            setEnabled(cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            int col = table.getSelectedColumn();

            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
            if (cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR)) {
                try {
                    Object value = cb.getData(CellTransferable.CELL_DATA_FLAVOR);
                    System.out.println(value);
                    table.setValueAt(value, row, col);

                } catch (UnsupportedFlavorException | IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }

    public static class CellTransferable implements Transferable {

        public static final DataFlavor CELL_DATA_FLAVOR = new DataFlavor(Object.class, "application/x-cell-value");

        private Object cellValue;

        public CellTransferable(Object cellValue) {
            this.cellValue = cellValue;
        }

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{CELL_DATA_FLAVOR};
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return CELL_DATA_FLAVOR.equals(flavor);
        }

        @Override
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (!isDataFlavorSupported(flavor)) {
                throw new UnsupportedFlavorException(flavor);
            }
            return cellValue;
        }

    }

}

Now, maybe you’d like to provide a runnable example that demonstrates it not
working…



 类似资料:
  • 使用“复制链接”按钮复制链接 导航到其他输入/文本字段 用Ctrl+V粘贴到字段中,并读取该字段的内容以验证 我的测试: 但是,没有任何内容粘贴到该输入(和return)。 谢了!

  • 在Linux上不接触鼠标,在命令模式下的VIM和系统剪贴板之间复制粘贴的最快方法是什么?

  • 问题是,从vim到剪贴板的复制/粘贴停止工作。我不知道为什么。。。 在中,我也没有看到和缓冲区... 这是我的。vimrc,如果需要的话。 有什么建议吗? 谢谢

  • 问题内容: 我正在寻找一个如何将文本复制到iOS剪贴板的干净示例,然后可以在其他应用程序中使用/粘贴该文本。 此功能的优点是可以快速复制文本,而无需传统文本复制的标准文本突出显示功能。 我假设键类在其中,但是在它们提供的代码示例中找不到相关的区域。 问题答案: 如果您只需要纯文本,则可以使用属性。它既可读又可写: (从剪贴板中 读取数据时 ,UIPasteboard文档还建议您首先检查一下,“以避

  • 我可以使vim粘贴从和到系统的剪贴板?

  • 问题内容: 我想从Java中的系统剪贴板中粘贴。我该怎么做? 问题答案: 尽管机器人类可以工作,但它不像直接使用系统剪贴板那样优雅,例如: