Select 仅单元格,但在 table 中突出显示整行

Select only the cell but highlight the entire row in a table

在我的table中我设置了

table.setCellSelectionEnabled(true);  

这样我就可以让用户 select 一个单独的单元格,然后使用 ctrl-c copy/paste 其他地方的单元格内容。但是,我也希望突出显示整行(就像只用 table.setRowSelectionAllowed(true) 完成的那样)。有没有一种简单的方法可以完成此操作,还是需要 table 的自定义渲染器?

因为您只想将选定的单元格复制到 clipboard.I 已完成 this.This 会将选定的单元格内容 [在 Ctrl+C 上] 仅复制到剪贴板,同时整行是也突出显示

我已经实现了仅复制,如果需要,您可以实现剪切和粘贴。

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTable;

public class TableTest extends JFrame {
JTable table;

public TableTest() {
    table = new JTable();
    this.add(table);
    //Adding table with four columns and rows
    table.setModel(new javax.swing.table.DefaultTableModel(
            new Object[][]{
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String[]{
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
    ));
    //Adding table listener for Copy Ctrl+C
    addTableListener();
}

private void addTableListener() {
    table.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.isControlDown()) {
                if (e.getKeyCode() == KeyEvent.VK_C) {
                    copy();
                }
            }
        }
    });
}

private void cancelEditing() {
    if (table.getCellEditor() != null) {
        table.getCellEditor().cancelCellEditing();
    }
}

public void copy() {
    cancelEditing();//To cancel editing if the cell is in edited mode
    int row = table.getSelectedRow();
    int col = table.getSelectedColumn();
    if (row != -1 && col != -1) {
        Object value = table.getValueAt(row, col);
        value = value != null ? value : "";
        StringSelection stringSelection = new StringSelection(value.toString());
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, stringSelection);
    }
}

public static void main(String[] args) {
    TableTest test = new TableTest();
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.pack();
    test.setLocationRelativeTo(null);
    test.setVisible(true);
}
}