How do I populate a JTable?

6

I have a fairly simple java application that connects to a database, in the console I type the query I want to pass by parameter to the executeQuery. Now I need to pass all this to a graphical interface. Is there any way I can create just one window, and pass the data as they are willing to the GUI?

I have nothing done yet, I have a JTable just declared, because I did not find any good tutorial on how to do it. In my program I have a JTextArea that receives a query, then I will need to dynamically display this table as soon as I click the execute button. My question is how popular is this table.

    
asked by João Neto 10.06.2014 в 06:03
source

1 answer

7

To create and populate a JTable, you should actually add the data to a DefaultTableModel and then set it as the table model.

I've done an example with comments that follow below:

JTable table = new JTable();
String[] nomesColunas = {"nome", "endereco", "telefone"};
//essa lista terá as linhas da sua JTable, preenchi abaixo apenas como exemplo
List<String[]> lista = new ArrayList<>();
//aqui você fará um while percorrendo seu result set e adicionando na lista
//while(resultset.next()) {
lista.add(new String[]{"Joao", "rua um", "1234-5678"});
lista.add(new String[]{"Henrique", "rua 42", "1122-3344"});
lista.add(new String[]{"Manuel", "av 7 de setembro", "8765-4321"});
//} //fim while
//crie um defaultablemodel com as informações acima
DefaultTableModel model = new DefaultTableModel(
        lista.toArray(new String[lista.size()][]), nomesColunas);
//define o model da sua tabela
table.setModel(model);
//adiciona no contentpane, coloque dentro de um JScrollPane pois caso 
//contrário não aparecerão os nomes das colunas
contentPane.add(new JScrollPane(table), BorderLayout.CENTER);
    
answered by 10.06.2014 / 16:29
source