Página Inicial do Fórum > Java Básico

Alguém me ajude por favor.... Urgente!!!!



Criar novo tópico   Responder tópico
  1. Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    Pessoal, estou tentando fazer um combo, onde a cada mudança, muda a tabela selecionada.

    [code]
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.sql.*;
    import java.util.*;

    public class gui extends JFrame
    {
    private javax.swing.JComboBox jComboBox1;
    private static Connection con;
    private static Statement Stmt;
    private static ResultSet rs;
    private String nome;

    public gui() {
    initComponents();
    this.setTitle("Cadastro de Clientes");
    this.setSize(650,200);
    ComboBox.setBorder(new javax.swing.border.BevelBorder(0));
    ComboBox.setBackground(java.awt.Color.white);
    ComboBox.setBackground(java.awt.Color.white);

    String url="jdbcdbc:CtrVendas";
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
    con=DriverManager.getConnection(url);

    }
    catch(Exception e){
    JOptionPane.showMessageDialog(null,"Erro de acesso ao banco!",
    "Mensagem",JOptionPane.ERROR_MESSAGE);
    }


    ComboEscolha.addItem("Cliente");
    ComboEscolha.addItem("Vendedor");
    ComboEscolha.addItem("Produto");
    }

    /** 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.
    */
    private void initComponents() {
    ComboBox = new javax.swing.JComboBox();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    ComboEscolha = new javax.swing.JComboBox();

    getContentPane().setLayout(null);

    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    }
    });

    getContentPane().add(ComboBox);
    ComboBox.setBounds(70, 20, 240, 21);

    jLabel1.setText("Clientes");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(20, 20, 60, 15);

    jLabel2.setText("Escolha:");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(440, 20, 50, 15);

    ComboEscolha.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(java.awt.event.ItemEvent evt) {
    ComboEscolhaItemStateChanged(evt);
    }
    });

    getContentPane().add(ComboEscolha);
    ComboEscolha.setBounds(420, 40, 90, 21);

    pack();
    }

    private void ComboEscolhaItemStateChanged(java.awt.event.ItemEvent evt) {

    try
    {
    Stmt=con.createStatement();
    rs= Stmt.executeQuery("Select * from TbVendedor");
    }

    catch(SQLException ex)
    {
    JOptionPane.showMessageDialog(null,"Erro ao Executar a Consulta!",
    "Mensagem",JOptionPane.ERROR_MESSAGE);
    }

    if (ComboEscolha.getSelectedIndex()==0)
    {

    int i=0;
    while(rs.next())
    {
    nome= rs.getString("Nome");
    ComboBox.addItem(nome);
    }
    }


    /* else if(ComboEscolha.getSelectedIndex()==1)
    {
    rs= Stmt.executeQuery("Select * from TbCliente");

    int i=0;
    while(rs.next())
    {
    nome= rs.getString("Nome");
    ComboBox.addItem(nome);
    }
    }
    **/

    }

    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    new gui().show();
    }

    // Variables declaration - do not modify
    private javax.swing.JComboBox ComboBox;
    private javax.swing.JComboBox ComboEscolha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration

    }

    Alguém sabe o que está errado??

    Erros:

    C:\trabalhofatec\gui.java:110: unreported exception java.sql.SQLException; must be caught or declared to be thrown
    while(rs.next())
    ^
    C:\trabalhofatec\gui.java:112: unreported exception java.sql.SQLException; must be caught or declared to be thrown
    nome= rs.getString("Nome");
    ^




  1. cleuber_s
    Posts:219


    Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    Coloque dentro de um bloco try...catch(SQLException e)...
    _________________
    JavaFree.org




  1. ronaldtm
    Posts:2317


    Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    Fernanda, eu já respondi essa pergunta pra você: http://www.javafree.com.br/forum/viewtopic.php?p=48939#48939[/url]

    O erro é o mesmo.

    Não é um erro de JDBC, mas sim de compilação. Vou tentar explicar melhor:

    Exceções checadas, como a SQLException precisam ser tratadas (com o bloco try/catch), ou relançada (declaração throws SQLException no método).

    O erro de compilação que você enviou:


    mostra exatamente o erro:

    C:\trabalhofatec\gui.java:110: unreported exception
    unreported exception java.sql.SQLException; must be caught or declared to be thrown

    ou

    No arquivo C:\trabalhofatec\gui.java, linha 110, houve uma exceção não relatada java.sql.SQLException; deve ser capturada (com o bloco try/catch) ou declarada para ser lançada ('throws SQLException' na declaração do método).

    No seu código, você já fez isso em outros trechos, veja bem como está sendo feito e repita o tratamento na linha do erro.

    Mais uma observação: por favor, não mande a mesma dúvida para mais de um fórum. Decida qual o fórum mais apropriado e envie a dúvida uma única vez. Caso ela esteja em um lugar inapropriado, um moderador irá movê-la para onde ela tem mais chance de ser respondida, deixando um aviso sobre a mudança.

    Tetsuo
    _________________
    In fact, people who study design methods without also practicing design are almost always frustrated designers who have no sap in them, who have lost, or never had, the urge to shape things. Such a person will never be able to say anything sensible about "how" to shape things either. (Christopher Alexander)




  1. Raphael
    Posts:217


    Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    Só complementando, para sua saúde, utilize uma ide para trabalhar... O Eclipse é uma boa pedida, é grátis e todo mundo usa! E como a maioria das IDEs, sempre aponta onde tem um erro de compilação e a possível solução. Isso com certeza te pouparia dor de cabeça.
    _________________
    kthksbye!




  1. Edinei Manica
    Posts:2456


    Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    Mas, eu acho que ela usa o NetBeans !




  1. Raphael
    Posts:217


    Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    Edinei Manica
    Mas, eu acho que ela usa o NetBeans !





    Nunca usei o Net Beans, por isso não sei o funcionamento dele (quando usava trabalhava com swing eu usava o JBuilder)... mas ele não aponta erros de compilação????
    _________________
    kthksbye!




  1. Edinei Manica
    Posts:2456


    Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    Raphael
    Edinei Manica
    Mas, eu acho que ela usa o NetBeans !





    Nunca usei o Net Beans, por isso não sei o funcionamento dele (quando usava trabalhava com swing eu usava o JBuilder)... mas ele não aponta erros de compilação????



    Acho que sim, eu só usei o netbeans na faculdade !
    Mas, ele apontava os erros de compilação !




  1. Raphael
    Posts:217


    Comment Arrow

    Publicado em: 09/04/2009 23:18:44

    então tah... mas pelo jeito eu ainda voh esperar para usar o NetBeans...
    _________________
    kthksbye!




  1. Relacionados





Novo tópico   Responder tópico     Índice do forum -> Java Básico