[英]Change copy behavior of a JTable cell
By default, when you try to copy from a JTable
, the toString
method of the value(s) being copied are sent to the clipboard. 默认情况下,当您尝试从
JTable
复制时,将要复制的值的toString
方法发送到剪贴板。 How can I change this behavior for one class of objects? 如何为一类对象更改此行为?
Let's say I have a table with two columns for simplicity's sake. 为了简单起见,假设我有一个包含两列的表。 The first column has
Boolean
s in it and the second column has String
s. 第一列包含
Boolean
,第二列包含String
。 Currently when you copy a Boolean
, you get either true
or false
. 当前,当您复制
Boolean
,将得到true
或false
。 How could I change this behavior to place an arbitrary string on the clipboard (say t
for true
and f
for false
) without changing the copy behavior of String
? 如何更改此行为以在剪贴板上放置任意字符串(例如,
t
表示true
, f
表示false
)而不更改String
的复制行为?
Here's a SSCCE where you can copy / paste from a JTable
. 这是一个SSCCE,您可以在其中从
JTable
复制/粘贴。
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.AbstractTableModel;
public class ChangeCopyBehavior {
private static class TestModel extends AbstractTableModel {
private static final long serialVersionUID = -774558262249729206L;
@Override
public int getRowCount() {
return 4;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public Class<?> getColumnClass(int col) {
return col == 0 ? Boolean.class : String.class;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 1) {
return "String";
} else {
return rowIndex % 2 == 0;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JTable table = new JTable(new TestModel());
table.setCellSelectionEnabled(true);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JScrollPane(table), BorderLayout.CENTER);
panel.add(new JTextArea("Paste stuff here"), BorderLayout.SOUTH);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}
Create a custom TransferHandler to export the data in whatever format you want. 创建一个自定义TransferHandler,以所需的任何格式导出数据。
Here is a link to the old ExtendedDnDDemo from the Swing tutorial that show an example of a custom TableTransferHandler. 这是Swing教程中旧的ExtendedDnDDemo的链接,其中显示了自定义TableTransferHandler的示例。
See this SO question where I gave an example of custom copy-behavior using a SwingX JXTable
. 看到这个SO问题 ,在此我举了一个使用SwingX
JXTable
的自定义复制行为 JXTable
。 However, that same approach can be used with a regular JTable
但是,相同的方法可以用于常规
JTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.