解决方法:
重写JTable类的键盘监听事件。
/**
* 20240313 add hzh
*/
table.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent e) {
//System.out.println("22222");
System.out.println("keycode"+e.getKeyCode());
if(e.getKeyCode()==KeyEvent.VK_CONTROL&&e.getKeyCode() == KeyEvent.VK_C ||e.isControlDown()&&e.getKeyCode() == KeyEvent.VK_C|| (!e.isControlDown())&&e.getKeyCode() == KeyEvent.VK_C)
{
System.out.println("复制事件");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //获得系统粘贴板
table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
String selectStr=ObjectUtils.toString(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
System.out.println("复制文本:" + selectStr);
StringSelection textInfoSelected = new StringSelection(selectStr); //建立一个粘贴板内容实例.
clipboard.setContents(textInfoSelected, null); //将textInfoSelected加入到粘贴板中;
AIFClipboard aifclipboard = AIFPortal.getClipboard();
aifclipboard.clearClipboard();
}
}
@Override
public void keyReleased(KeyEvent e) {
//System.out.println("22222");
System.out.println("keycode"+e.getKeyCode());
if(e.getKeyCode()==KeyEvent.VK_CONTROL&&e.getKeyCode() == KeyEvent.VK_C ||e.isControlDown()&&e.getKeyCode() == KeyEvent.VK_C|| (!e.isControlDown())&&e.getKeyCode() == KeyEvent.VK_C)
{
System.out.println("复制事件");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // 获得系统粘贴板
String selectStr = ObjectUtils
.toString(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
StringBuffer sbf=new StringBuffer();
// 检查以确保我们仅选择了单元格的
// 相邻块
int numcols = table.getSelectedColumnCount();
int numrows = table.getSelectedRowCount();
int[] rowsselected = table.getSelectedRows();
int[] colsselected = table.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(table.getValueAt(rowsselected[i], colsselected[j]).toString().replace("\r\n", " ").replace("\n", " ").replace("\r", " "));
if (j < numcols - 1)
sbf.append(" ");
}
sbf.append("\n");
}
System.out.println("复制文本:" + sbf.toString());
StringSelection textInfoSelected = new StringSelection(sbf.toString()); // 建立一个粘贴板内容实例.
clipboard.setContents(textInfoSelected, null); // 将textInfoSelected加入到粘贴板中;
AIFClipboard aifclipboard = AIFPortal.getClipboard();
aifclipboard.clearClipboard();
}
}
@Override
public void keyTyped(KeyEvent arg0) {
System.out.println("33333");
}
});