JTable headers to clipboard (WORKING CODE)

The following code gets selected fields in JTable into

a system clipboard. Now how to get the table headers

to the clipboard too, so that I don't have to retype

them when pasting the clipboard contents to MS Excel for example.

StringSelection stsel;

StringBuffer sbf = new StringBuffer();

int rowCount = tblDataTable.getRowCount ();

int colCount = tblDataTable.getColumnCount();

String headerCnt = tblDataTable.getAccessibleContext();

for (int col = 0; col < colCount; col++) {

sbf.append(tblDataTable.getValueAt(col));

}

for (int row = 0; row < rowCount; row++) {

for (int col = 0; col < colCount; col++) {

sbf.append(tblDataTable.getValueAt(row,col));

if (col < colCount - 1) { sbf.append("\t"); }

}

sbf.append("\n");

}

stsel = new StringSelection(sbf.toString());

java.awt.datatransfer.Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();

system.setContents(stsel, stsel);

[1052 byte] By [aulo] at [2007-9-26 1:48:00]
# 1

Hi there!

Try this:

JTableHeader tblHeader = tblDataTable.getTableHeader();

TableColumnModel model = tblHeader.getColumnModel();

int headCount = model.getColumnCount();

for (int col=0; col < headCount; col++) {

sbf.append (model.getColumn(col).getHeaderValue());

if (col < headCount - 1) { sbf.append("\t"); }

}

sbf.append("\n");

instead of

String headerCnt = tblDataTable.getAccessibleContext();

for (int col = 0; col < colCount; col++) {

sbf.append(tblDataTable.getValueAt(col));

}

Hope this helps,

Kurt.

leukbr at 2007-6-29 2:47:44 > top of Java-index,Core,Core APIs...
# 2
You're the man! It worked!Regards,Aulo
aulo at 2007-6-29 2:47:44 > top of Java-index,Core,Core APIs...