By default, when you try to copy from a JTable
, the toString
method of the value(s) being copied are sent to the clipboard. 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. Currently when you copy a Boolean
, you get either true
or 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
?
Here's a SSCCE where you can copy / paste from a 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);
}
});
}
}