Copy Jtable Column to Clipboard?

Asked

Viewed 216 times

0

I have here a table template with four columns and several rows filled in which I take the database. I would like to create an Action button that copies columns 2 and 3 at once to the clipboard, and so be able to paste, for example, in an Excel or other places. It is possible?

Follow the Jtable model I’m wearing.

import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;

public class MinhaTabelaEditavel extends AbstractTableModel {
private ArrayList linhas = null;
private String[] colunas = null;

public MinhaTabelaEditavel (ArrayList lin, String[] col){
    setLinhas(lin);
    setColunas(col);    
}

public ArrayList getLinhas() {
    return linhas;
}

public void setLinhas(ArrayList dados) {
    this.linhas = dados;
}

public String[] getColunas() {
    return colunas;
}

public void setColunas(String[] nome) {
    this.colunas = nome;
}

public int getColumnCount(){
    return colunas.length;
}

public int getRowCount (){
    return linhas.size();
}

public String getColumnName (int numCol){
    return colunas[numCol];
}

public Object getValueAt (int numLin, int numCol){
    Object[] linha = (Object[])getLinhas().get(numLin);
    return linha[numCol];
}

@Override
public boolean isCellEditable(int row, int column) {
return true;
}
  • Please provide a [mcve] of your table with some data. This code is not executable.

1 answer

2

In accordance with this answer in Soen, you will need to convert the text to a text type that you can copy to the clipboard, then just send the text normally, through the class Clipboard, as below:

StringSelection stringSelection = new StringSelection(<texto a ser copiado>);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);

In your case, just recover the text to be copied from the desired columns using the method getValueAt() and moving on to the StringSelection.

Take an example:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.