我尝试为我的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);
}
}
答案 0 :(得分:2)
使用Keybindings进行Swing,因为KeyListener
/ KeyAdapter
在与Swing组件一起使用时会出现已知问题。
似乎可以正常使用以上实现:
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.KeyStroke;
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"});
tab.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK, true), "CTRL C");
tab.getActionMap().put("CTRL C", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
ClipboardTable.copyToClipboard(ClipboardTable.tab); // whole row is copied instead of only Cell
}
});
jf.add(tab);
jf.pack();
jf.setVisible(true);
}
}
答案 1 :(得分:1)
答案 2 :(得分:1)
你应该
KeyListener
Action
。作为Action
,您可以使用TransferHandler.getCopyAction()
TransferHandler
上添加自定义JTable
,以防您对标准行为不满意