我尝试为我的 JTable 做一个简单的ctrl+ c,但是当使用控制按钮时,整行被复制,而不是指定的单元格。如何获得想要的效果?
public class ClipboardTable {
private static final Clipboard clipboard = Toolkit.getDefaultToolkit()
.getSystemClipboard();
public static JTable tab;
public static void copyToClipboard(JTable ctaable) {
StringBuilder str = new StringBuilder("");
for (int i = 0; i < ctaable.getSelectedRows().length; i++) {
str.append(ctaable.getValueAt(ctaable.getSelectedRows()[i], 0));
}
StringSelection strsel = new StringSelection(str.toString());
clipboard.setContents(strsel, strsel);
System.out.println("expected: "+str.toString());
}
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object[][] data = {{1,2,3},{5,6,7},{8,9,0}};
tab = new JTable(data, new String[] {"a","b","c"});
KeyListener searchKeyListen = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
ClipboardTable.copyToClipboard(ClipboardTable.tab); //this works fine
if (e.isControlDown()) {
if ((e.getKeyCode() == KeyEvent.VK_C)) {
ClipboardTable.copyToClipboard(ClipboardTable.tab); // whole row is copied instead of only Cell
}
}
}
};
tab.addKeyListener(searchKeyListen);
jf.add(tab);
jf.pack();
jf.setVisible(true);
}
}