如何在JXTreeTable的第二列插入数据?

问题描述 投票:0回答:0

我想在一个JXTreeTable的第二列中插入数据。JXTreeTable 其第一列由显示成本中心的名称组成(这些成本中心是树节点,它们是 DefaultMutableTreeTableNode),第二列应该显示这个成本中心的成本值(float)。但是,我无法使第二列的数据出现。有谁知道如何修正我的代码,使数据显示在第二列?

我的代码是这样的。

package com.camposmart.telas;

import com.camposmart.dal.ModuloConexao;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javafx.scene.control.TreeTableColumn;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
import org.jdesktop.swingx.treetable.DefaultTreeTableModel;
import org.jdesktop.swingx.treetable.TreeTableNode;

/**
 *
 * @author Arroiz
 */
public class TelaRelatorioFinanceiro2 extends javax.swing.JInternalFrame {

    Connection conexao = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    PreparedStatement pst2 = null;
    ResultSet rs2 = null;

    /**
     * Creates new form TelaRelatorioFinanceiro
     */
    public TelaRelatorioFinanceiro2() {
        initComponents();
        conexao = ModuloConexao.conector();
        preencherJTreeTable();
    }

    public void preencherJTreeTable() { //método responsável por todo o preenchimento da JXTreeTable

        try {
            TreeTableNode root1 = new DefaultMutableTreeTableNode("Relatório Financeiro");
            ArrayList<String> nomeColunas = new ArrayList();
            nomeColunas.add("Centro de Custo");
            nomeColunas.add("Valor");
            DefaultTreeTableModel model = new DefaultTreeTableModel(root1, nomeColunas);
            trtbRelatorioFinanceiro.setTreeTableModel(model);
            DefaultMutableTreeTableNode root = (DefaultMutableTreeTableNode) model.getRoot();
            trtbRelatorioFinanceiro.setShowGrid(true, true);
            trtbRelatorioFinanceiro.setColumnControlVisible(true);
            trtbRelatorioFinanceiro.packAll();


            String sqlContarCentros = "select count(*) from centrocusto"; //contar quantidade de registros na tabela centrocusto.
            pst = conexao.prepareStatement(sqlContarCentros);
            rs = pst.executeQuery();
            rs.next();
            int quantidadeCentros = rs.getInt(1);

            ArrayList<Integer> idCentrosPreenchidos = new ArrayList(); //criar arraylist para colocar os ids dos centros que ja foram preenchidos na jTree
            ArrayList<DefaultMutableTreeTableNode> nomeCentrosPreenchidos = new ArrayList();
            Map<String, DefaultMutableTreeTableNode> mapeamentoDeVariaveis = new HashMap<String, DefaultMutableTreeTableNode>();
            ArrayList<String> nomeCentrosPreenchidos2 = new ArrayList();
            int contadorPreenchimentos = 0; //contador da quantidade de registros que já foram preenchidos na JTree

            DefaultMutableTreeTableNode geral = new DefaultMutableTreeTableNode("Geral"); //Preencher o centro de custo Geral na Jtree
            root.add(geral);
            mapeamentoDeVariaveis.put("Geral", geral);
            nomeCentrosPreenchidos.add(geral);
            nomeCentrosPreenchidos2.add("Geral");

            //marcar no array que o id do centro de custo Geral já foi preenchido na Jtree:
            String sqlPegarIdGeral = "select id from centrocusto where pai = ?";
            pst = conexao.prepareStatement(sqlPegarIdGeral);
            pst.setInt(1, 0);
            rs = pst.executeQuery();
            rs.next();
            int idGeral = rs.getInt(1);
            idCentrosPreenchidos.add(idGeral);

            //Inicialização de variáveis que compoem o looping:
            contadorPreenchimentos++; //Adicionar 1 ao contadorPreenchimentos.
            int percorredorDeArray = 0;
            boolean idPreenchidoTemFilho = false;
            String sqlVerSeTemFilho;
            String sqlPegarIdENomeFilhos;
            int idFilho;
            String nomeFilho;
            String sqlPegarNome;
            String sqlPegarId;
            String nomePai;
            ArrayList<DefaultMutableTreeTableNode> nomeFilhoNode = new ArrayList(); //Cria uma lista que guarda vários nós da Jtree
            int id;
            String sqlSomarValoresCusto;
            ArrayList<DefaultMutableTreeTableNode> valorFilhoNode = new ArrayList(); //Cria uma lista que guarda vários nós da Jtree
            int contadorFilhoNode = 0;

            //Looping de preenchimento:
            while (contadorPreenchimentos < quantidadeCentros) { //looping que continua até preencher todos os centros de custo
                idPreenchidoTemFilho = false;
                while ((percorredorDeArray < contadorPreenchimentos) && (idPreenchidoTemFilho == false)) { //Ver se os centros de custo que já foram preenchidos no array tem filho (desde o primeiro item do array até o último todas as vezes)

                    sqlVerSeTemFilho = "select tem_filho from centrocusto where id = ?";
                    pst = conexao.prepareStatement(sqlVerSeTemFilho);
                    pst.setInt(1, idCentrosPreenchidos.get(percorredorDeArray));
                    rs = pst.executeQuery();
                    rs.next();

                    idPreenchidoTemFilho = rs.getBoolean(1);

                    if (idPreenchidoTemFilho) {
                        sqlPegarIdENomeFilhos = "select id, nome from centrocusto where pai = ?";
                        pst = conexao.prepareStatement(sqlPegarIdENomeFilhos);
                        pst.setInt(1, idCentrosPreenchidos.get(percorredorDeArray));
                        rs = pst.executeQuery();

                        while (rs.next()) {
                            idFilho = rs.getInt(1); //pega o id do primeiro filho, depois do segundo, etc. se houver
                            nomeFilho = rs.getString(2); //pega o nome do primeiro filho, depois do segundo, etc. se houver
                            if (idCentrosPreenchidos.contains(idFilho) == false) { //se no array que grava os ids dos centro preenchidos já estiver cadastrado o id deste filho...

                                sqlPegarNome = "select nome from centrocusto where id = ?"; //pega o id do pai do filho selecionado para dar o comando pai.add(filho) na jtree
                                pst2 = conexao.prepareStatement(sqlPegarNome);
                                pst2.setInt(1, idCentrosPreenchidos.get(percorredorDeArray));
                                rs2 = pst2.executeQuery();
                                rs2.next();

                                nomePai = rs2.getString(1);

                                nomeFilhoNode.add(new DefaultMutableTreeTableNode(nomeFilho));
                                mapeamentoDeVariaveis.put(nomeFilho, nomeFilhoNode.get(contadorPreenchimentos - 1));
                                mapeamentoDeVariaveis.get(nomePai).add(nomeFilhoNode.get(contadorPreenchimentos - 1));
                                idCentrosPreenchidos.add(idFilho);
                                nomeCentrosPreenchidos.add(nomeFilhoNode.get(contadorPreenchimentos - 1));
                                nomeCentrosPreenchidos2.add(nomeFilho);
                                contadorPreenchimentos++; //adicionar 1 ao contadorPreenchimentos
                            }
                        }
                    }
                    percorredorDeArray++; //adicionar 1 ao percorredor de array
                    idPreenchidoTemFilho = false;
                }
            }
            trtbRelatorioFinanceiro.expandAll(); //expandir todos os nós

            for (String n : nomeCentrosPreenchidos2) { //for each para percorrer o arraylist para cada elemento existente

                sqlPegarId = "SELECT id FROM centrocusto WHERE nome = ?"; //pegar o id a partir do nome contido no arraylist dos nomes dos centros preenchidos
                pst = conexao.prepareStatement(sqlPegarId);
                pst.setString(1, n);
                rs = pst.executeQuery();
                rs.next();

                id = rs.getInt(1);

                sqlSomarValoresCusto = "SELECT SUM(valor_custo) FROM custo WHERE centrocusto = ?"; //somar os registros do campo valor_custo da tabela custo
                pst = conexao.prepareStatement(sqlSomarValoresCusto);
                pst.setInt(1, id);
                rs = pst.executeQuery();
                rs.next();

                valorFilhoNode.add(new DefaultMutableTreeTableNode(rs.getFloat(1)));

                    if (trtbRelatorioFinanceiro.getTreeTableModel().getValueAt(mapeamentoDeVariaveis.get(n), 0).toString().equals(n)) {
                        trtbRelatorioFinanceiro.setEditable(true);
                        trtbRelatorioFinanceiro.getTreeTableModel().setValueAt(valorFilhoNode.get(contadorFilhoNode), mapeamentoDeVariaveis.get(n), 1);
                    }
                contadorFilhoNode++;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jspRelatorioFinanceiro = new javax.swing.JScrollPane();
        trtbRelatorioFinanceiro = new org.jdesktop.swingx.JXTreeTable();

        setClosable(true);
        setMaximizable(true);
        setTitle("Relatório Financeiro");

        trtbRelatorioFinanceiro.setClosedIcon(null);
        trtbRelatorioFinanceiro.setOpenIcon(null);
        trtbRelatorioFinanceiro.setRootVisible(true);
        jspRelatorioFinanceiro.setViewportView(trtbRelatorioFinanceiro);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jspRelatorioFinanceiro, javax.swing.GroupLayout.DEFAULT_SIZE, 663, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jspRelatorioFinanceiro, javax.swing.GroupLayout.DEFAULT_SIZE, 722, Short.MAX_VALUE)
        );

        setBounds(0, 0, 679, 758);
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jspRelatorioFinanceiro;
    private org.jdesktop.swingx.JXTreeTable trtbRelatorioFinanceiro;
    // End of variables declaration                   
}

所有的查询都从数据库中返回了正确的值 但是当我使用setValueAt()来表示第二列时 它并没有被填满,如下图所示JXTreeTable not showing 2nd column's data

我试着把第二列的值写成了: DefaultMutableTreeTableNode 但没有用,我试过设置可编辑(true),但也没有用,我想创建一个JXTreeTable,它的第一列由显示成本中心的名称(就是树节点,是DefaultMutableTreeTableNode的实例)组成,然后再创建一个JXTreeTable。

java netbeans swingx jxtreetable defaultmutabletreenode
© www.soinside.com 2019 - 2024. All rights reserved.