Fórum como listar dados no combobox aplicação java #486777
25/07/2014
0
tenho a classe que faz a conexão onde se encontram tambem metodos que as query como UPDATE E DELETE E SELECT.
e tenho um tela que fiz direto com codigo onde se encotra minha combobox...
mais não consigo listar nada nela.
desde já agradeço:
Márcio Azevedo
Curtir tópico
+ 0Post mais votado
29/07/2014
Ronaldo Lanhellas
Gostei + 1
Mais Posts
01/08/2014
Márcio Azevedo
package studio;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class ConexaoBanco {
public Connection conectar;
public Statement execucao;
public ResultSet resultado;
String driver= "org.postgresql.Driver";
String caminho="jdbc:postgresql://localhost:5432/studio";
String senha= "milestone1";
String usuario="postgres";
//TelaCliente dados;
public ConexaoBanco()
{
try
{
// Este é um dos meios para registrar um driver
Class.forName(driver);
}
catch (ClassNotFoundException ex)
{
JOptionPane.showMessageDialog(null,"erro"+ex);
}
try
{
// Registrado o driver, vamos estabelecer uma conexão
conectar=DriverManager.getConnection(caminho,usuario,senha);
// Após estabelecer a conexão com o banco de dados
// o método createStatement de conectar para criar o Statement
execucao=conectar.createStatement();
}
catch (SQLException ex)
{
JOptionPane.showMessageDialog(null,"erro"+ex);
}
}
////////////////METÓTODO RESPONSAVEL CADASTRAR CLIENTE NO BD/////////////////////////
public void cadastrarCliente(Pessoa cliente)
{
try
{
// executar o seguinte comando SQL :
execucao.execute("INSERT INTO cliente (telefone,nome,cpf,endereco) VALUES('"+cliente.getTelefone()+""
+ "','"+cliente.getNome()+"','"+cliente.getCpf()+""
+ "',"+ " '"+cliente.getEndereco()+"');");
}
catch (SQLException ex)
{
JOptionPane.showMessageDialog(null,"erro ao cadastrar!"+ex);
}
}
public void Desconecta()
{
try
{
conectar.close();
JOptionPane.showMessageDialog(null,"DESCONECTANDO DO BANCO");
}
catch (SQLException ex)
{
JOptionPane.showMessageDialog(null,"ERRO AO DESCONECTAR. \nERRO " +ex.getMessage());
}
}
/////////////////////////////////METÓDO RESPONSÁVEL POR REALIZAR CONSULTA NO BAD/////////////////////
public ResultSet buscaClientes(String nome)
{
try
{
// executar o seguinte comando SQL :
resultado = execucao.executeQuery("SELECT * FROM cliente WHERE nome like '%"+nome+"%'");
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
return resultado;
}
/////////////////////////////////METÓDO RESPONSÁVEL POR ALTERAR DADOS PREVIAMENTE CADASTRO NO BD/////////////////////
ResultSet alterarCliente(Pessoa cliente, String cod_cliente)
{
try
{
// executar a seguinte comando SQL :
resultado= execucao.executeQuery("UPDATE cliente SET nome = '"+cliente.getNome()+"', telefone = '"+cliente.getTelefone()+""
+ "', cpf = '"+cliente.getCpf()+"', endereco = '"+cliente.getEndereco()+"' WHERE cod_cliente = "+cod_cliente+"");
}
catch (SQLException e)
{
// JOptionPane.showMessageDialog(null,"ERRO AO ATUALIZAR!\n"+e.getMessage());
}
return resultado;
}
///////////////////////////////METÓDO RESPONSÁVEL POR EXCLUIR DADOS PREVIAMENTE GRAVADOS NO BD///////////////////////
public ResultSet excluirCliente(int codigo)
{
try
{
// Vamos executar o seguinte comando SQL :
resultado = execucao.executeQuery("DELETE FROM cliente WHERE cod_cliente = '"+codigo+"'");
}
catch (SQLException e)
{
// JOptionPane.showMessageDialog(null,"ERRO!\n"+e.getMessage());
}
return resultado;
}
}
AQUI É A MINHA CLASSE RESPONSÁVEL POR RECUPERAR DADOS DO BD.
Gostei + 0
01/08/2014
Márcio Azevedo
package studio;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.ResultSet;
import java.text.ParseException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import javax.swing.text.PlainDocument;
public class TelaCliente extends JFrame {
private JTable tabela;
private JLabel labelNome;
private DefaultTableCellRenderer centro;
// private JTextField campoNome;
private JFormattedTextField campoNome;
private JLabel labelCpf;
// private JTextField campoCpf;
private JFormattedTextField campoCpf;
private JLabel labelEnder;
private JFormattedTextField campoEnder;
private JLabel tel;
private JFormattedTextField telcampo;
// private JTextField telcampo;
private JLabel labelcod;
private JTextField campocod;
private JComboBox combo;
private JButton botaoCadastrar;
ConexaoBanco conexao=new ConexaoBanco();
public TelaCliente()
{
super("Cadastro do Cliente");
// conexao
Container tela = this.getContentPane();
FlowLayout layout = new FlowLayout();
tela.setLayout(null);
Pessoa cliente = new Pessoa();
combo=new JComboBox();
combo.setBounds(70,265, 250,35);
labelNome = new JLabel();
labelNome.setText("Nome:");
labelNome.setBounds(10,10,250,40);
campoCpf=new JFormattedTextField();
try
{
campoCpf.setFormatterFactory (new DefaultFormatterFactory(new MaskFormatter("###.###.###-##")));
}
catch (ParseException ex){}
//campoNome = new JTextField("informe aqui o nome do cliente");
campoNome= new JFormattedTextField();
campoNome.setBounds(70,10,250,40);
campoNome.addFocusListener(new java.awt.event.FocusAdapter()
{
//Ação do cursos para JTextField
public void focusGained (java.awt.event.FocusEvent evt)
{
if (campoNome.getText().equals("DIGITE O NOME AQUI"))
{
campoNome.setText("");
}
}
@Override
public void focusLost (java.awt.event.FocusEvent evt)
{
if (campoNome.getText().equals(""))
{
campoNome.setText("DIGITE O NOME AQUI");
}
}
});
campoNome.setDocument(new PlainDocument(){
public void insertString (int offs, String str, AttributeSet a)
throws BadLocationException{
str = str.replaceAll("[^A-Za-z ]", "");
super.insertString(offs, str.toUpperCase(),a);
}
});
// campoNome.setPreferredSize(new Dimension(200,25));
labelCpf = new JLabel();
labelCpf.setText("CPF:");
labelCpf.setBounds(10,60,250,40);
labelcod=new JLabel();
labelcod.setText("Código cliente");
campocod=new JTextField();
// campocod.setPreferredSize(new Dimension(200,25));
/////////////////////////////////////////////////////////////////////////////////////////////
// campoCpf = new JTextField("informe aqui o CPF do cliente");
campoCpf=new JFormattedTextField();
try {
campoCpf.setFormatterFactory (new DefaultFormatterFactory(new MaskFormatter("###.###.###-##")));
}
catch (ParseException ex){}
campoCpf.setBounds(70,60,250,40);
campoCpf.setText("digite o cpf");
// campoCpf.setPreferredSize(new Dimension(200,25));
//////////////////////////////////////////////////////////////////////////////////////
labelEnder = new JLabel();
labelEnder.setText("Endereço:");
labelEnder.setBounds(10,160,250,40);
campoEnder=new JFormattedTextField();
campoEnder.setDocument(new PlainDocument(){
public void insertString (int offs, String str, AttributeSet a)
throws BadLocationException{
str = str.replaceAll("[^A-Za-z ]", "");
super.insertString(offs, str.toUpperCase(),a);
}
});
campoEnder.setBounds(70,160 ,250, 40);
// campoEnder.setPreferredSize(new Dimension(200,25));
/////////////////////////////////////////////////////////////////////////////////////
tel = new JLabel();
tel.setText("Telefone:");
tel.setBounds(10,110, 250,40);
//telcampo = new JTextField("informe aqui o nº do telefone cliente");
telcampo= new JFormattedTextField();
try {
telcampo.setFormatterFactory (new DefaultFormatterFactory(new MaskFormatter("(###) ####-####")));
} catch (ParseException ex) {}
telcampo.setBounds(70,110,250,40);
// telcampo.setPreferredSize(new Dimension(200,25));
botaoCadastrar = new JButton();
botaoCadastrar.setText("Cadastrar");
botaoCadastrar.setBounds(70,220, 110,35);
//botaoCadastrar.setPreferredSize(new Dimension(200,25));
botaoCadastrar.addActionListener(
new java.awt.event.ActionListener(){
@Override
public void actionPerformed(ActionEvent ae)
{
/// acao pra fazer a tabela ser preenchida ///
Pessoa cliente = new Pessoa();
cliente.setNome(campoNome.getText());
cliente.setCpf(campoCpf.getText());
cliente.setTelefone(telcampo.getText());
cliente.setEndereco(campoEnder.getText());
conexao.cadastrarCliente(cliente);
campoNome.setText("");
campoCpf.setText("");
telcampo.setText("");
campoEnder.setText("");
}
}
);
tela.add(labelNome);
tela.add(campoNome);
tela.add(labelCpf);
tela.add(campoCpf);
tela.add(tel);
tela.add(telcampo);
tela.add(labelEnder);
tela.add(campoEnder);
tela.add(labelcod);
tela.add(campocod);
tela.add(botaoCadastrar);
tela.add(combo);
this.setSize(485,530);
this.setVisible(false);
this.setLocationRelativeTo(null);
this.setResizable(false);
}
}
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)