JTable não aparece

11 respostas
M
Olá, estou fazendo um programa com interface gráfica, ela é composta por um JFrame que contém vários JPanel dentro dele com cardLayout. Um desses Painéis, tem um botão "BConsultaNotaBim" que realiza uma consulta ao Banco de Dados e deveria retornar uma tabela. A consulta é feita, mas a tabela não aparece! Já tentei setVisible e nada! Tenho a impressão de que ela deve estar escondida atrás de outros painéis ou não está sendo criada...sei lá... Será que podem me ajudar? Muito obrigada desde já por qualquer colaboração :D Segue o Código
package ideal21;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;


/**
 *
 * @author Cáh
 */
public class MenuPrincipal extends javax.swing.JFrame {

    /** Creates new form MenuPrincipal */
    public MenuPrincipal() {
        initComponents();
        EmBranco.setVisible(true);
        PConsultaNotaBim.setVisible(false);
        PConsultaNotaAno.setVisible(false);
    }

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

        PConsultaNotaBim = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        aluno_ConsultaNotaBim = new javax.swing.JTextField();
        bim_ConsultaNotaBim = new javax.swing.JTextField();
        ano_ConsultaNotaBim = new javax.swing.JTextField();
        BConsultaNotaBim = new javax.swing.JButton();
        EmBranco = new javax.swing.JPanel();
        PConsultaNotaAno = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        aluno_ConsultaNotaAno = new javax.swing.JTextField();
        ano_ConsultaNotaAno = new javax.swing.JTextField();
        BConsultaNotaAno = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        ConsultaNotaBim = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(950, 650));
        getContentPane().setLayout(new java.awt.CardLayout());

        PConsultaNotaBim.setMinimumSize(new java.awt.Dimension(900, 650));
        PConsultaNotaBim.setPreferredSize(new java.awt.Dimension(900, 650));
        PConsultaNotaBim.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Consulta de Notas por Bimestre");
        PConsultaNotaBim.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 40, -1, -1));

        jLabel2.setText("Aluno:");
        PConsultaNotaBim.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 90, -1, -1));

        jLabel3.setText("Bimestre:");
        PConsultaNotaBim.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 90, -1, -1));

        jLabel4.setText("Ano:");
        PConsultaNotaBim.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 130, -1, -1));
        PConsultaNotaBim.add(aluno_ConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 90, 420, -1));
        PConsultaNotaBim.add(bim_ConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(770, 90, 60, -1));
        PConsultaNotaBim.add(ano_ConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 130, 70, -1));

        BConsultaNotaBim.setText("Consultar");
        BConsultaNotaBim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BConsultaNotaBimActionPerformed(evt);
            }
        });
        PConsultaNotaBim.add(BConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 130, -1, -1));

        getContentPane().add(PConsultaNotaBim, "card2");

        javax.swing.GroupLayout EmBrancoLayout = new javax.swing.GroupLayout(EmBranco);
        EmBranco.setLayout(EmBrancoLayout);
        EmBrancoLayout.setHorizontalGroup(
            EmBrancoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 900, Short.MAX_VALUE)
        );
        EmBrancoLayout.setVerticalGroup(
            EmBrancoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 650, Short.MAX_VALUE)
        );

        getContentPane().add(EmBranco, "card3");

        PConsultaNotaAno.setMinimumSize(new java.awt.Dimension(900, 650));
        PConsultaNotaAno.setPreferredSize(new java.awt.Dimension(900, 650));
        PConsultaNotaAno.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel5.setText("Consulta de Notas por Ano");
        PConsultaNotaAno.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 40, -1, -1));

        jLabel6.setText("Aluno:");
        PConsultaNotaAno.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 90, -1, -1));

        jLabel8.setText("Ano:");
        PConsultaNotaAno.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 130, -1, -1));
        PConsultaNotaAno.add(aluno_ConsultaNotaAno, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 90, 420, -1));
        PConsultaNotaAno.add(ano_ConsultaNotaAno, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 130, 70, -1));

        BConsultaNotaAno.setText("Consultar");
        BConsultaNotaAno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BConsultaNotaAnoActionPerformed(evt);
            }
        });
        PConsultaNotaAno.add(BConsultaNotaAno, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 130, -1, -1));

        getContentPane().add(PConsultaNotaAno, "card2");

        jMenu1.setText("Matrícula");

        jMenuItem1.setText("Matricular Aluno");
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Cadastros");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("Consultas");

        ConsultaNotaBim.setText("Consulta de Notas Bimestrais");
        ConsultaNotaBim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConsultaNotaBimActionPerformed(evt);
            }
        });
        jMenu3.add(ConsultaNotaBim);

        jMenuItem2.setText("Consulta de Notas Anual");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem2);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

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

    private void ConsultaNotaBimActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:
        //EmBranco.setVisible(false);
        EmBranco.setVisible(false);
        PConsultaNotaAno.setVisible(false);

        PConsultaNotaBim.setVisible(true);
    }                                               

    private void BConsultaNotaBimActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        // TODO add your handling code here:
        String url = "jdbc:mysql://localhost:3306/ideal16";
        String login = "root";
        String senha = "";
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("\nDriver carregado com sucesso!\n");
            try {
                Connection conn = DriverManager.getConnection(url, login, senha);
                try {
                    String sql = "SELECT * FROM notas where cod_BIMESTRE = "+bim_ConsultaNotaBim.getText()+";"; // nome da consulta
        //String sql="INSERT into disciplina (cod_disciplina, nome_disciplina) values ("+jTextField1.getText()+",'"+jTextField2.getText()+"');";
                    Statement stm = conn.createStatement();
                     try {
                            ResultSet rs1 = stm.executeQuery(sql); // aqui é executada a consulta
         //stm.execute(sql); // insere os dados

                           displayResultSet(rs1);
                          
                           System.out.println("\nConsulta realizada com sucesso!!!\n");
                           stm.close(); // fecha a conexão
                    }
                    catch ( SQLException sqlex ) {
                        sqlex.printStackTrace();
                        System.out.println("\nErro no ResultSet");
                    }
                }
                catch (Exception ex) {
                        System.out.println("\nErro no statement!");
                }
            }
            catch (Exception ex) {
                System.out.println("\nErro no connection!");
            }
        }
        catch (Exception ex) {
            System.out.println("\nDriver nao pode ser carregado!");
        }
        
    }                                                

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

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        EmBranco.setVisible(false);
        PConsultaNotaAno.setVisible(true);
        PConsultaNotaBim.setVisible(false);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MenuPrincipal().setVisible(true);
            }
        });
    }

    public void displayResultSet (ResultSet rs)throws SQLException {
        boolean moreRecords = rs.next();
        if (!moreRecords) {
            JOptionPane.showMessageDialog(this,"Sem Registros");
            setTitle("Nothing!");
            return;
        }
        setTitle("Nome da Tabela");
         //nome da tabela
        Vector coluna = new Vector();
        Vector linha = new Vector();

        try { // tenta pegar os títulos da colunas
            ResultSetMetaData titulocoluna = rs.getMetaData();
            for (int i = 1; i<=titulocoluna.getColumnCount(); ++i) {
                coluna.addElement(titulocoluna.getColumnName(i));
            }
            do { // obtem dados da linha
                linha.addElement(getNextRow(rs, titulocoluna));
            }
            while (rs.next());
            // cria a tabela com os resultados
            JTable table = new JTable(linha, coluna);
                        

            //adiciona função scroll
            JScrollPane scroller = new JScrollPane(table);
            
            getContentPane().add(scroller, BorderLayout.CENTER);
           validate();
            
            
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
       
   }
    public Vector getNextRow( ResultSet rs, ResultSetMetaData titulocoluna ) throws SQLException {
        Vector currentRow = new Vector();
        for ( int i = 1; i <= titulocoluna.getColumnCount(); ++i )
        switch( titulocoluna.getColumnType( i ) ) {
        case Types.VARCHAR:
        currentRow.addElement( rs.getString( i ) );
        break;
        case Types.INTEGER:
        currentRow.addElement( new Long( rs.getLong( i ) ) );
        break;
        }
        return currentRow;
    }

    // Variables declaration - do not modify
    private javax.swing.JButton BConsultaNotaAno;
    private javax.swing.JButton BConsultaNotaBim;
    private javax.swing.JMenuItem ConsultaNotaBim;
    private javax.swing.JPanel EmBranco;
    private javax.swing.JPanel PConsultaNotaAno;
    private javax.swing.JPanel PConsultaNotaBim;
    private javax.swing.JTextField aluno_ConsultaNotaAno;
    private javax.swing.JTextField aluno_ConsultaNotaBim;
    private javax.swing.JTextField ano_ConsultaNotaAno;
    private javax.swing.JTextField ano_ConsultaNotaBim;
    private javax.swing.JTextField bim_ConsultaNotaBim;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    // End of variables declaration

}

11 Respostas

U

Olá mimila pelo o que vc comentou pode ser uns dos problemas vc ja tentou faze-lo separadamente contendo um form e tabela???

L

Oi,

Não faltou definir um tamanho para seu JScrollPane ?

Tchauzin!

M
Acabei de tentar, Um JFrame e colocando a tabela dentro dele e ela não aparece.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on 18/11/2009, 09:10:04
 */

package testetabela;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
/**
 *
 * @author Cáh
 */
public class NewJFrame extends javax.swing.JFrame {

    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
    }

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

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(692, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(37, 37, 37))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addComponent(jButton1)
                .addContainerGap(463, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String url = "jdbc:mysql://localhost:3306/ideal16";
        String login = "root";
        String senha = "";
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("\nDriver carregado com sucesso!\n");
            try {
                Connection conn = DriverManager.getConnection(url, login, senha);
                try {
                    String sql = "SELECT * FROM notas where cod_BIMESTRE = 2;"; // nome da consulta
        //String sql="INSERT into disciplina (cod_disciplina, nome_disciplina) values ("+jTextField1.getText()+",'"+jTextField2.getText()+"');";
                    Statement stm = conn.createStatement();
                     try {
                            ResultSet rs1 = stm.executeQuery(sql); // aqui é executada a consulta
         //stm.execute(sql); // insere os dados


                           displayResultSet(rs1);

                           System.out.println("\nConsulta realizada com sucesso!!!\n");
                           stm.close(); // fecha a conexão
                    }
                    catch ( SQLException sqlex ) {
                        sqlex.printStackTrace();
                        System.out.println("\nErro no ResultSet");
                    }
                }
                catch (Exception ex) {
                        System.out.println("\nErro no statement!");
                }
            }
            catch (Exception ex) {
                System.out.println("\nErro no connection!");
            }
        }
        catch (Exception ex) {
            System.out.println("\nDriver nao pode ser carregado!");
        }
    }
    public void displayResultSet (ResultSet rs)throws SQLException {
        boolean moreRecords = rs.next();
        if (!moreRecords) {
            JOptionPane.showMessageDialog(this,"Sem Registros");
            setTitle("Nothing!");
            return;
        }
        setTitle("Nome da Tabela");
         //nome da tabela
        Vector coluna = new Vector();
        Vector linha = new Vector();

        try { // tenta pegar os títulos da colunas
            ResultSetMetaData titulocoluna = rs.getMetaData();
            for (int i = 1; i<=titulocoluna.getColumnCount(); ++i) {
                coluna.addElement(titulocoluna.getColumnName(i));
            }
            do { // obtem dados da linha
                linha.addElement(getNextRow(rs, titulocoluna));
            }
            while (rs.next());
            // cria a tabela com os resultados
            JTable table = new JTable(linha, coluna);


            //adiciona função scroll
            JScrollPane scroller = new JScrollPane(table);

            getContentPane().add(scroller, BorderLayout.CENTER);

           validate();


        }
        catch (SQLException ex) {
            ex.printStackTrace();
            System.out.println("\nerro na criação da tabela");
        }

   }
    public Vector getNextRow( ResultSet rs, ResultSetMetaData titulocoluna ) throws SQLException {
        Vector currentRow = new Vector();
        for ( int i = 1; i <= titulocoluna.getColumnCount(); ++i )
        switch( titulocoluna.getColumnType( i ) ) {
        case Types.VARCHAR:
        currentRow.addElement( rs.getString( i ) );
        break;
        case Types.INTEGER:
        currentRow.addElement( new Long( rs.getLong( i ) ) );
        break;
        }
        return currentRow;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    // End of variables declaration

}
M

lina,
desculpe, sou novata e fiz esse código com a ajuda de um amigo, como eu defino esse tamanho?
Obrigada.

U

vai um exemplo.

vlw
abs

M

Oi lina, consegui fazê-la aparecer acrescentando um scroller.setSize
mas não apareceram todos os dados da tabela, apenas os inteiros, acho que o método getNewRow está com problema

M

Consegui resolver o problema com o método getNextRow, mas nao tem como deixar a tabela se auto-dimensionar?
Porque tenho tabelas de vários tamanhos

outra coisa, como mudar o nome das colunas que vem da tabela?
tipo, tem uma que é alunos_cod_aluno e eu gostaria que fosse apenas aluno

iii… quando voltei pro projeto anterior (Tabela dentro de JPanel, dentro de JFrame) ela não apareceu mais =/

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MenuPrincipal.java
 *
 * Created on 17/11/2009, 23:16:46
 */

package ideal21;
import com.sun.org.apache.bcel.internal.generic.TABLESWITCH;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;


/**
 *
 * @author Cáh
 */
public class MenuPrincipal extends javax.swing.JFrame {

    /** Creates new form MenuPrincipal */
    public MenuPrincipal() {
        initComponents();
        EmBranco.setVisible(true);
        PConsultaNotaBim.setVisible(false);
        PConsultaNotaAno.setVisible(false);
    }

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

        PConsultaNotaBim = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        aluno_ConsultaNotaBim = new javax.swing.JTextField();
        bim_ConsultaNotaBim = new javax.swing.JTextField();
        ano_ConsultaNotaBim = new javax.swing.JTextField();
        BConsultaNotaBim = new javax.swing.JButton();
        EmBranco = new javax.swing.JPanel();
        PConsultaNotaAno = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        aluno_ConsultaNotaAno = new javax.swing.JTextField();
        ano_ConsultaNotaAno = new javax.swing.JTextField();
        BConsultaNotaAno = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        ConsultaNotaBim = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(950, 650));
        getContentPane().setLayout(new java.awt.CardLayout());

        PConsultaNotaBim.setMinimumSize(new java.awt.Dimension(900, 650));
        PConsultaNotaBim.setPreferredSize(new java.awt.Dimension(900, 650));
        PConsultaNotaBim.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Consulta de Notas por Bimestre");
        PConsultaNotaBim.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 40, -1, -1));

        jLabel2.setText("Aluno:");
        PConsultaNotaBim.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 90, -1, -1));

        jLabel3.setText("Bimestre:");
        PConsultaNotaBim.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 90, -1, -1));

        jLabel4.setText("Ano:");
        PConsultaNotaBim.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 130, -1, -1));
        PConsultaNotaBim.add(aluno_ConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 90, 420, -1));
        PConsultaNotaBim.add(bim_ConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(770, 90, 60, -1));
        PConsultaNotaBim.add(ano_ConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 130, 70, -1));

        BConsultaNotaBim.setText("Consultar");
        BConsultaNotaBim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BConsultaNotaBimActionPerformed(evt);
            }
        });
        PConsultaNotaBim.add(BConsultaNotaBim, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 130, -1, -1));

        getContentPane().add(PConsultaNotaBim, "card2");

        javax.swing.GroupLayout EmBrancoLayout = new javax.swing.GroupLayout(EmBranco);
        EmBranco.setLayout(EmBrancoLayout);
        EmBrancoLayout.setHorizontalGroup(
            EmBrancoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 900, Short.MAX_VALUE)
        );
        EmBrancoLayout.setVerticalGroup(
            EmBrancoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 650, Short.MAX_VALUE)
        );

        getContentPane().add(EmBranco, "card3");

        PConsultaNotaAno.setMinimumSize(new java.awt.Dimension(900, 650));
        PConsultaNotaAno.setPreferredSize(new java.awt.Dimension(900, 650));
        PConsultaNotaAno.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel5.setText("Consulta de Notas por Ano");
        PConsultaNotaAno.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 40, -1, -1));

        jLabel6.setText("Aluno:");
        PConsultaNotaAno.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 90, -1, -1));

        jLabel8.setText("Ano:");
        PConsultaNotaAno.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 130, -1, -1));
        PConsultaNotaAno.add(aluno_ConsultaNotaAno, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 90, 420, -1));
        PConsultaNotaAno.add(ano_ConsultaNotaAno, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 130, 70, -1));

        BConsultaNotaAno.setText("Consultar");
        BConsultaNotaAno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BConsultaNotaAnoActionPerformed(evt);
            }
        });
        PConsultaNotaAno.add(BConsultaNotaAno, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 130, -1, -1));

        getContentPane().add(PConsultaNotaAno, "card2");

        jMenu1.setText("Matrícula");

        jMenuItem1.setText("Matricular Aluno");
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Cadastros");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("Consultas");

        ConsultaNotaBim.setText("Consulta de Notas Bimestrais");
        ConsultaNotaBim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConsultaNotaBimActionPerformed(evt);
            }
        });
        jMenu3.add(ConsultaNotaBim);

        jMenuItem2.setText("Consulta de Notas Anual");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem2);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

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

    private void ConsultaNotaBimActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:
        //EmBranco.setVisible(false);
        EmBranco.setVisible(false);
        PConsultaNotaAno.setVisible(false);

        PConsultaNotaBim.setVisible(true);
    }                                               

    private void BConsultaNotaBimActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        // TODO add your handling code here:
        String url = "jdbc:mysql://localhost:3306/ideal16";
        String login = "root";
        String senha = "";
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("\nDriver carregado com sucesso!\n");
            try {
                Connection conn = DriverManager.getConnection(url, login, senha);
                try {
                    String sql = "SELECT * FROM notas where cod_BIMESTRE = "+bim_ConsultaNotaBim.getText()+";"; // nome da consulta
        //String sql="INSERT into disciplina (cod_disciplina, nome_disciplina) values ("+jTextField1.getText()+",'"+jTextField2.getText()+"');";
                    Statement stm = conn.createStatement();
                     try {
                            ResultSet rs1 = stm.executeQuery(sql); // aqui é executada a consulta
         //stm.execute(sql); // insere os dados
                            

                           displayResultSet(rs1);
                          
                           System.out.println("\nConsulta realizada com sucesso!!!\n");
                           stm.close(); // fecha a conexão
                    }
                    catch ( SQLException sqlex ) {
                        sqlex.printStackTrace();
                        System.out.println("\nErro no ResultSet");
                    }
                }
                catch (Exception ex) {
                        System.out.println("\nErro no statement!");
                }
            }
            catch (Exception ex) {
                System.out.println("\nErro no connection!");
            }
        }
        catch (Exception ex) {
            System.out.println("\nDriver nao pode ser carregado!");
        }
        
    }                                                

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

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        EmBranco.setVisible(false);
        PConsultaNotaAno.setVisible(true);
        PConsultaNotaBim.setVisible(false);
    }                                          

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MenuPrincipal().setVisible(true);
            }
        });
    }

    public void displayResultSet (ResultSet rs)throws SQLException {
        boolean moreRecords = rs.next();
        if (!moreRecords) {
            JOptionPane.showMessageDialog(this,"Sem Registros");
            setTitle("Nothing!");
            return;
        }
        setTitle("Nome da Tabela");
         //nome da tabela
        Vector coluna = new Vector();
        Vector linha = new Vector();

        try { // tenta pegar os títulos da colunas
            ResultSetMetaData titulocoluna = rs.getMetaData();
            for (int i = 1; i<=titulocoluna.getColumnCount(); ++i) {
                coluna.addElement(titulocoluna.getColumnName(i));
            }
            do { // obtem dados da linha
                linha.addElement(getNextRow(rs, titulocoluna));
            }
            while (rs.next());
            // cria a tabela com os resultados
            JTable table = new JTable(linha, coluna);
                        

            //adiciona função scroll
            JScrollPane scroller = new JScrollPane(table);
            scroller.setSize(900, 100);
            getContentPane().add(scroller, BorderLayout.CENTER);
          
           validate();
            
            
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            System.out.println("\nerro na criação da tabela");
        }
       
   }
    public Vector getNextRow( ResultSet rs, ResultSetMetaData titulocoluna ) throws SQLException {
        Vector currentRow = new Vector();
        for ( int i = 1; i <= titulocoluna.getColumnCount(); ++i )
        switch( titulocoluna.getColumnType( i ) ) {
        case Types.VARCHAR:
        currentRow.addElement( rs.getString( i ) );
        break;
        case Types.INTEGER:
        currentRow.addElement( new Long( rs.getLong( i ) ) );
        break;

        case Types.DECIMAL:
            currentRow.addElement(rs.getFloat(i));
            break;
        }
        return currentRow;
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton BConsultaNotaAno;
    private javax.swing.JButton BConsultaNotaBim;
    private javax.swing.JMenuItem ConsultaNotaBim;
    private javax.swing.JPanel EmBranco;
    private javax.swing.JPanel PConsultaNotaAno;
    private javax.swing.JPanel PConsultaNotaBim;
    private javax.swing.JTextField aluno_ConsultaNotaAno;
    private javax.swing.JTextField aluno_ConsultaNotaBim;
    private javax.swing.JTextField ano_ConsultaNotaAno;
    private javax.swing.JTextField ano_ConsultaNotaBim;
    private javax.swing.JTextField bim_ConsultaNotaBim;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    // End of variables declaration                   

}
M

outra coisa, como mudar o nome das colunas que vem da tabela?
tipo, tem uma que é alunos_cod_aluno e eu gostaria que fosse apenas aluno

L

Oi,

Você quer dar um Alter na coluna da base de dados? é isso?

Tchauzin!

M

Não, eu não quero mudar o meu banco, queria apenas que o título da coluna da tabela que se refere ao alunos_cod_aluno aparecesse para o usuário como Código do Aluno

S

Olá

vai um exemplo:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package assistenciadesktop;

import java.sql.ResultSet;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author silvio
 */

public class ClassInicializaTable {
    static  java.sql.Statement stmt;
    static String mnome, macao;
    static Object id;
    public int linhatabela;
    static ResultSet rs;
    public String [] Colunas;
    public int [] TamanhoCol;
    public JTable jTable1 = new JTable();
    public JScrollPane scroller = new JScrollPane(jTable1);
    public DefaultTableModel aModel = new DefaultTableModel();;
    
public void ClassInicializaTable () {
}
    
public void montaTabela(String[] nomeColunas, int [] tamanhoColunas,int [] posicaoTabela) throws Exception {
   String[] tableColumnsName = nomeColunas;        

   DefaultTableModel aModel = new DefaultTableModel(nomeColunas, 0) {

      @Override
      public Class getColumnClass(int column) {
         Class returnValue;
         if ((column >= 0) && (column < getColumnCount())) {
            if (getValueAt(0, column) != null) {
               returnValue = getValueAt(0, column).getClass();
            } else {
              returnValue = Object.class;
            }
         } else {
            returnValue = Object.class;
         }
         return returnValue;
      }

      @Override
      public boolean isCellEditable(int row, int col) {
         return false;
      }
  };
        
 aModel.setColumnIdentifiers(nomeColunas);      
 Colunas = nomeColunas;
 TamanhoCol = tamanhoColunas;
 jTable1.setModel(aModel);  
 scroller.setBounds(posicaoTabela[0], posicaoTabela[1], posicaoTabela[2], posicaoTabela[3]);

}

public void preencheTabela( boolean pesquisa, ResultSet rs,String[] nomeColunas, int [] tamanhoColunas,int [] posicaoTabela, String [] nomeCampos) throws Exception {
    
   String[] tableColumnsName = nomeColunas;        

   DefaultTableModel aModel = new DefaultTableModel(nomeColunas, 0) {

      @Override
      public Class getColumnClass(int column) {
         Class returnValue;
         if ((column >= 0) && (column < getColumnCount())) {
            if (getValueAt(0, column) != null) {
               returnValue = getValueAt(0, column).getClass();
            } else {
              returnValue = Object.class;
            }
         } else {
            returnValue = Object.class;
         }
         return returnValue;
      }

      @Override
      public boolean isCellEditable(int row, int col) {
         return false;
      }
   };
        
   aModel.setColumnIdentifiers(nomeColunas);      
   Colunas = nomeColunas;
   TamanhoCol = tamanhoColunas;
   jTable1.setModel(aModel);  
   scroller.setBounds(posicaoTabela[0], posicaoTabela[1], posicaoTabela[2], posicaoTabela[3]);

   if (pesquisa) {    
      int colNo = Colunas.length;
      while(rs.next()){
         Object[] objects = new Object[colNo];
         for(int i = 0; i < colNo; i++) {
            objects[i] = rs.getObject(nomeCampos[i]);
         }   
         aModel.addRow(objects);
      }
      jTable1.setModel(aModel);   
      jTable1.setFillsViewportHeight(true);
      jTable1.getTableHeader().setReorderingAllowed(false);
   }
} 

}

como usar:

public class FrameOrdemServico extends MyInternalFrame {

    public ClassInicializaTable tabela = new ClassInicializaTable();

.....

        String [] colunasTab = {"Nº Orçamento","Data Orçamento","Hora","Tipo Equipamento","Marca","Modelo","Nº Série"};
        int [] tamanhoCol = {10,10,10,100};
        int [] posicaoTab = {50,(int) (getHeight - (getHeight * pos+.04 )),600,150};
        String [] nomeCampos = { "id_ordemservico","dataordemservico","horaordemservico",
                                 "descricao","marca","modelo","numeroserie"};

        colunasTabela = colunasTab;
        tamanhoColunas = tamanhoCol;
        posicaoTabela = posicaoTab;
        nomeDosCampos = nomeCampos;

        tabela.preencheTabela(false,rs,colunasTabela, tamanhoColunas, posicaoTabela,nomeDosCampos);
        jPanel2.add(tabela.scroller);
        jPanel2.add(tabela.scroller).setVisible(true);

acho que isso pode ajudar você, boa sorte.

Silvio Guedes

Criado 18 de novembro de 2009
Ultima resposta 23 de nov. de 2009
Respostas 11
Participantes 4