Ajuda com SWING / JTABLE - NETBEANS [RESOLVIDO]

Amigos,

Estou lendo o dia inteiro sobre SWING e estou com problemas pra entender.

É o seguinte, estou fazendo um programa que varre um diretório “x”, quando encontra um file ele lê o arquivo atrás de algumas evidências. (Essa parte está OK, dando um System.out.println vejo todas informações necessárias)

Mas agora to precisando montar uma tela simples com SWING para mostrar tudo isso. To tentando com o Netbeans que já é uma mão na Roda mas acho q to precisando de outra roda pra anda kkkkkkk. Até agora só consegui criar um botão que inicia meu metodo de pesquisa xD

Preciso de sugestões/dicas de como fazer isso.

Vou deixa aí o código que fiz para varrer e ler o arquivo atrás de evidencias.

[code]import java.awt.Component;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;

public class Diretorio {

String pal[] = {"numberCode:" , "resourceCode:"};
String stringPosIgual;
String linha;
String subStringLinha;
double afterEqual;
int contador;
int posicaoIgual;
private static Component mainPanel;



public void find( ){    
    JFileChooser jFileChooser1 = new JFileChooser();   
    jFileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);  
    int returnVal = jFileChooser1.showDialog(mainPanel, null);  
    if (returnVal == JFileChooser.APPROVE_OPTION) {  
       String entrada = jFileChooser1.getSelectedFile().getAbsolutePath();
        varreDiretorio(entrada);
    }  
   
}


public void varreDiretorio(String entrada){
    File diretorio = new File(entrada);
    if (diretorio.isDirectory()){
            File[] file = diretorio.listFiles();  
            for (File y : file ){
                if(y.isFile()){
                    leArquivo(y);
                }else if (y.isDirectory()){
                    String voltaEntrada = y.getPath();
                    varreDiretorio(voltaEntrada);                  
                }
            }
        }
}

  public void leArquivo(File entrada) {
      
    try {  
        BufferedReader in = new BufferedReader(new FileReader(entrada)); 
        System.out.println( "\n" + entrada + "\n");
        
        for (int i = 1; (linha = in.readLine()) != null; i++ ){ //percorre arquivo
            for (int j = 0; j < pal.length; j++){ // percorre array de String com as TAG
                if (linha.contains(pal[j])){ // Verifica se a TAG existe no documento
                    int posicaoTag = linha.indexOf(pal[j]);//Pega índice da TAG
                    subStringLinha = (linha.substring(posicaoTag, linha.length()));//Nova String apartir da TAG
                    
                    if(subStringLinha.contains("=")){
                        posicaoIgual = subStringLinha.lastIndexOf("=");
                        stringPosIgual = (subStringLinha.substring(posicaoIgual+1));
                        
                        afterEqual = converteStringParaNumero(stringPosIgual);

                        if(afterEqual > 0){
                        contador++;
                        //System.out.println("linha: \t" + i + "\t TAG: \t" + pal[j]);
                        System.out.println("Numero Linha: " + i);
                        System.out.println("Linha: " + linha);
                        System.out.println("subStringLinha: " + subStringLinha);
                        System.out.println("stringPosIgual: " + stringPosIgual + "\n");
                        }
                    }
                }
            }
        }
        
    } catch (Exception e) {  
        System.err.println("Erro " + e.getMessage());   
    }
}   
  
  
  public double converteStringParaNumero(String string){
      char[] chars = string.toCharArray();
      List <String> stringList = new ArrayList <String>();
      
      for (int i=0; (i< chars.length) && (Character.isDigit(chars[i])) ;i++)
            stringList.add(chars[i]+"");
      
      String finalStr = "";   
      for (String str : stringList) {  
           if (finalStr.isEmpty()) {  
                finalStr = str;  
           }else{  
               finalStr = finalStr + str;  
           }  
      }  
      double afterEqualDouble = Double.parseDouble(finalStr);
      return afterEqualDouble;
  }

}//Class[/code]

Não vou postar a classe do swing pq só tem um botão que chama o Método find()

É qual realmente é a dificuldade? em usar os eventos? nos gerenciadores de layout? ou em usar o netbeans?

Oi,

Você deverá usar o JFrame ou o JDialog para montar uma janela onde terá esse JFileChooser para escolher os arquivos, é bom também colocar um JTable para a listagem dos arquivos e um JButton que execute essas alterações.

Eu utilizo o Eclipse com WindowBuilder que torna bem fácil a criação de telas Swing, não sei uma forma mais simples de fazer no Netbeans… :frowning:

Tópico movido para o fórum de interface gráfica.

Antes de usar o Netbeans, tente fazer uma interface na mão. Não parta pro construtor gráfico automático antes de entender como o Swing funciona.

Vini, é devido a urgência não tava com tempo para fazer o código na mão, mas com certeza quando tiver uma brecha vou estudar fazer na mão pq tava osso editar o código gerado pelo Netbeans.

MarcoAurelioBC, obrigado pela dica do Jtable acabei dando uma travada nele mas consegui fazer as alterações necessárias :slight_smile:

Vou deixar o código caso alguém tenha o mesmo problema, e tentar explicar um pouco da lógica que usei (com mta pesquisa no google e video aula no youtube hahahaha)

Criei uma classe simples com os atributos que precisava e seus metodos getters and setters (Essa não vou postar pq todo mundo sabe criar atributo e fazer get/set rsrsrs)

Depois disso criei uma classe que chamei de repositorio usando Design Pattern Singleton (Não sei se apliquei mto bem pq é a primeira vez q usso esse Pattern).
Resumidamente essa classe criei um Arraylist para armazenar todos objetos e Metodos para cadastro, consulta e um metodo que faz gestão do objeto instanciado.

public class RepositorioManager {
    
    private static RepositorioManager instance;
    private ArrayList<Dados> lista;
    
    private RepositorioManager(){
        lista = new ArrayList<Dados>();  
    }
    
    //Metodo verifica se ja existe objeto criado(instance) se não tiver ele cria caso exista ele retorna instance existente
    public static RepositorioManager getInstance(){
        
        if (instance == null){
            instance = new RepositorioManager();
        }
        return instance;
    }
    
    public void cadastrarDados(Dados d){
        lista.add(d);
        System.out.println(d.toString());
    }
    
    public ArrayList<Dados> obterListaProdutos() {
        
        return lista;
    }
}

Abaixo Tela de relatório, eu ainda me assusto com o código abaixo pq 95% foi gerado pelo netbeans rs


public class TelaRelatorios extends javax.swing.JFrame  {
    private NewJFrame telaPrincipal;


    /**
     * Creates new form TelaRelatorios
     */
    private TelaRelatorios() {
        initComponents();
        
        carregarJTable();

    }
    
    
    public TelaRelatorios(NewJFrame telaPrincipal) {
        this();
        
        this.telaPrincipal = telaPrincipal;
        
        
    }
    
//AQUI TA A MINHA TABELA :D
    private void carregarJTable() {
        ArrayList<Dados> lista = RepositorioManager.getInstance().obterListaProdutos();

        DefaultTableModel modelo = new javax.swing.table.DefaultTableModel();
        modelo.addColumn("Campo 0");
        modelo.addColumn("Campo 1");
        modelo.addColumn("Campo 2");
        modelo.addColumn("Campoa 3");
        

        if (lista.isEmpty()) {
            modelo.addRow(new String[]{"Sem dados",
                        null,
                        null,
                        null,});
        }
        
        for (int i = 0; i < lista.size(); i++) {
            Dados d = lista.get(i);


            // Alimenta as linhas de dados  
            modelo.addRow(new String[]{d.getCampo0(),
                        d.getCampo1(),
                        d.getCampo2()+ "",
                        d.getCampo3()+ ""});
        }

        jTable1.setModel(modelo);

    }

    /**
     * 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() {

        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jButton2.setText("Voltar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTable1FocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTable1FocusLost(evt);
            }
        });
        jTable1.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                jTable1InputMethodTextChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
        jLabel1.setText("Relatório produtos");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(jLabel1)
                        .add(0, 287, Short.MAX_VALUE))))
            .add(layout.createSequentialGroup()
                .add(0, 0, Short.MAX_VALUE)
                .add(jButton2))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 226, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButton2)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        this.dispose();
    }                                        

    private void formWindowClosed(java.awt.event.WindowEvent evt) {                                  
        // TODO add your handling code here:
        
        this.telaPrincipal.setEnabled(true);
        
        // NOVO CODIGO
        this.telaPrincipal.toFront();
        
    }                                 

    private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
        // TODO add your handling code here:
        System.out.println("form window activated");
        
        
    }                                    

    private void jTable1FocusGained(java.awt.event.FocusEvent evt) {                                    
        // TODO add your handling code here:
                
    }                                   

    private void jTable1FocusLost(java.awt.event.FocusEvent evt) {                                  
        // TODO add your handling code here:
        
    }                                 

    private void jTable1InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {                                               
        // TODO add your handling code here:
        System.out.println("jTable input changed now");
    }                                              

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaRelatorios().setVisible(true);
            }
        });
    }

    
    
    
   /**
    * Carrega novamente os dados do modelo
    */
    public void atualizarModelo() {
        
        System.out.println("atualizando modelo...");
        carregarJTable();
    }
    
    
    
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   

}