Um BD no jTable quem quiser pode pegar e comentar!

2 respostas
marciofermino

Ola amigos, depois de dias e dias e dias e dias …consegimos fazer, com ajuda de grandes amigos e noites mal dormidas… Ai esta o codigo…

Se alguem tiver um codigo para melhor isso ou outras sugestoes agradeço.
Tenho certeza que ira ajudar a muitos desenvolvedores…
Segue o codigo

import java.awt.Dimension;

import java.awt.Rectangle;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;
import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.table.DefaultTableModel;

@SuppressWarnings(“serial”)
public class Tela1 extends JFrame {

private JPanel jPanel = null;

private JLabel jLabel = null;

private JButton jButton = null;

private Connection con = null;

private JScrollPane jScrollPane = null;

private JTable jTable1 = null;

public Tela1() {
	super("Tela ");
	initialize();
	BdFromJtable();
	setVisible(true);
	setLocation(350, 200);

}

private void initialize() {
	this.setSize(new Dimension(495, 321));
	this.setContentPane(getJPanel());

}

private JPanel getJPanel() {
	if (jPanel == null) {
		jLabel = new JLabel();
		jLabel.setBounds(new Rectangle(126, 18, 223, 16));
		jLabel.setText("Valores Acessados do Banco de Dados");
		jPanel = new JPanel();
		jPanel.setLayout(null);
		jPanel.add(jLabel, null);
		jPanel.add(getJButton(), null);

		jPanel.add(getJScrollPane(), null);
	}
	return jPanel;
}

/**
 * Gera um modelo a partir de um ResultSet.
 * 
 * @param rs
 * @return Retorna um modelo de tabela contendo os dados de um ResulSet.
 * @throws java.lang.Exception
 * @Autor: Fabiano Fernandes
 */

public void inserirDados(ResultSet rs) {

	try {

		ResultSetMetaData metaData = rs.getMetaData();

		// nome das colunhas
		String[] colunas = new String[metaData.getColumnCount()];

		for (int i = 0; i < colunas.length; i++) {

			colunas[i] = metaData.getColumnName(i + 1);

		}

		// cria um modelo
		DefaultTableModel modelo = new DefaultTableModel(colunas, 0);

		// preenche o modelo
		while (rs.next()) {

			// uma linha
			String[] linha = new String[colunas.length];

			// adiciona valores na linha
			for (int i = 0; i < colunas.length; i++) {

				linha[i] = rs.getString(i + 1);

			}

			// adiciona a linha
			modelo.addRow(linha);

		}

		// seta o modelo na tabela
		jTable1.setModel(modelo);

	} catch (SQLException exc) {
		System.out.println(exc);
	}

}

/*
 * Aqui você faz alteração de acordo com seu Banco de dados
 */

public void Conexao() throws ClassNotFoundException, SQLException {

	// carregada a classe de driver do banco de dados
	//Class.forName("org.firebirdsql.jdbc.FBDriver");

	// estabele conexão com o banco de dados
	//con = DriverManager.getConnection(
	//		"jdbc:firebirdsql:localhost/3050:C:/DATABASE.GDB", "SYSDBA",
	//		"masterkey");
	
	Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	con = DriverManager.getConnection(
	 				"jdbc:odbc:dbdemos", "",
	 				"");
	 		
	JOptionPane.showMessageDialog(null,
			"Conexão realizada com sucesso! .. Massacre!!");
}

// Método que envia informações do BD para a JTable
public void BdFromJtable() {
	try {
		Conexao();
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery("SELECT * FROM items");
		inserirDados(rs);//este é o método que preenche
		rs.close();				// os valores da Tabela
		con.close();
	} catch (ClassNotFoundException cnfex) {
		cnfex.printStackTrace();
	} catch (SQLException sqlex) {
		sqlex.printStackTrace();
	}
}

/**
 * This method initializes jButton
 * 
 * @return javax.swing.JButton
 */
private JButton getJButton() {
	if (jButton == null) {
		jButton = new JButton();
		jButton.setBounds(new Rectangle(385, 252, 75, 26));
		jButton.setText("Fechar");

		jButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				System.exit(0);
			}
		});

	}
	return jButton;
}

/**
 * This method initializes jScrollPane
 * 
 * @return javax.swing.JScrollPane
 */
private JScrollPane getJScrollPane() {
	if (jScrollPane == null) {
		jScrollPane = new JScrollPane();
		jScrollPane.setBounds(new Rectangle(30, 47, 437, 110));
		jScrollPane.setViewportView(getJTable1());
	}
	return jScrollPane;
}

/**
 * This method initializes jTable
 * 
 * @return javax.swing.JTable
 */
private JTable getJTable1() {
	if (jTable1 == null) {
		jTable1 = new JTable();
	}
	return jTable1;
}

public static void main(String[] args) {
	Tela1 tela1 = new Tela1();
	tela1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

:stuck_out_tongue:

2 Respostas

Pedrosa

Cara você colocou tudo na mesma classe?, conexão, regra de negócio e view, eu separo em classes distintas, o que trará benefícios na manutenção.

silva.fernandes

Exatamente Predosa, como você falou, seguindo a arquitetura MVC (Model-View-Controller).

Mas esse código pode ajudar muitas pessoas que tem dificuldades em entender ou implementar o funcionamento de uma JTable.

Fica ai pra galerinha que ta começando …

He he he … bons estudos !!!

:lol: :lol: :lol:

Criado 11 de outubro de 2006
Ultima resposta 11 de out. de 2006
Respostas 2
Participantes 3