Throws!

Galera,

Queria saber como faço para contornar o seguinte.

Tenho um metodo que faz conexao ao BD
Porem ao chamar ele em outro metodo, da erro porque não tem declaração de “throws”.

[code]private void botaoLogarActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == botaoLogar) {
Logar();

   }
}[/code]

O metodo Logar() faz conexao ao banco, e tem a declaração de throws.
Quando chamo ele dentro da botaoLogarActionPerformed ele solicita throws nesse metodo, mas o NetBeans não permite inserir.

O que fazer neste caso?

Abraços

Vc pode tentar try / catch.

Mas coloque mais do código aí…tipo…a classe que tem o metodo do botao e o metodo logar…

Poe esse teu método ‘logar()’ dentro de um trycatch!

Abraços!!

Opa!
Deu certo…

Primário, mas nunca será esquecido.
Mais algo aprendido!

Valeu pessoal
Abraços

acho que o throws deve estar na declaração do metodo botaoLogarActionPerformed ou vc pode colocar a chamada do metodo Logar() dentro de um bloco try { } catch() { } para a exception , poderia por exemplo ser assim

    private void botaoLogarActionPerformed(java.awt.event.ActionEvent evt) {  
            if (evt.getSource() == botaoLogar) {  
              try {
               Logar();  
              } catch (minha exception)
               {
                  // trata o erro aqui 
               }        
           }  
       }  

Solução que funcionou

[code]private void botaoLogarActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == botaoLogar) {

        try{
            Verifica("ao", "ao*123");
        }catch (SQLException e1){
            e1.printStackTrace();
        }catch (ClassNotFoundException e1){
            e1.printStackTrace();
        }
   }
}[/code]

Questão:
Cada botao que crio, jTextField, etc… o NetBeans cria um metodo… po, o codigo fica enorme! Pra que isso?

[ ] 's

Ele pode estar tentando mapear todas a exceções que podem ocorrer.

Eu programo no eclipse e coloco somente os métodos que julgo necessários. Não tenho experiência no netbeans.

Pode colocar um exemplo aí pra tentar explicar a geração de código?

Quais métodos o NetBeans coloca?

Bom, as vezes, digo, sempre é melhor analisar o codigo antes de sair cuspindo perguntas…

Mas o fato é que entendi o porque de um metodo para cada JButton, JTextField e por aí a fora. Os eventos ActionPerformed ficam distribuidos pelos metodos bastando apenas escrever o que for necessario para o botão executar a ação desejada. Via Eclipse eu fazia uma grande classe ActionPerformed com varios if dentro, cada if referente a um botao ou algo que gere uma ação.

Segue o código com os metodos

[code]public class CLogar extends javax.swing.JFrame {

/** Creates new form CLogar */
public CLogar() {
    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() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    botaoLogar = new javax.swing.JButton();
    botaoSair = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Módulo Visualizador");
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    setName("Módulo Visualizador"); // NOI18N
    setResizable(false);

    jLabel1.setText("Usuario:");

    jLabel2.setText("Senha:  ");

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    botaoLogar.setText("Logar");
    botaoLogar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            botaoLogarActionPerformed(evt);
        }
    });

    botaoSair.setMnemonic('C');
    botaoSair.setText("Cancelar");
    botaoSair.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            botaoSairActionPerformed(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()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(botaoLogar)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(botaoSair, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(botaoLogar)
                .addComponent(botaoSair))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

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

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}

private void botaoSairActionPerformed(java.awt.event.ActionEvent evt) {

}

private void botaoLogarActionPerformed(java.awt.event.ActionEvent evt) {
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

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

// Variables declaration - do not modify
private javax.swing.JButton botaoLogar;
private javax.swing.JButton botaoSair;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration

}
[/code]

Ainda acho menos poluido a forma que eu utilizava:

public class CJanelaPrincipal extends JFrame {

	private JButton botaoCriar = new JButton("Criar Conta");
	private JButton botaoLogar = new JButton("Logar");
	private JLabel labelLogin = new JLabel("Nome de Usuario: ");
	private JLabel labelSenha = new JLabel("Senha:                     ");
	private JButton botaoSair = new JButton("Sair");
	private JTextField fieldUser = new JTextField(10);
	private JPasswordField fieldSenha = new JPasswordField(10);
	private JPanel painelUsuario;
	private JPanel painelSenha;
	private JPanel painelBotoes;
	
	public CJanelaPrincipal() {
		super("RP - VLB - CWB");
		setLocation(300, 200);
		setSize(250,165);
		setResizable(false);
		setVisible(true);

		painelUsuario = new JPanel(new FlowLayout(FlowLayout.LEFT));
		painelSenha = new JPanel(new FlowLayout(FlowLayout.LEFT));
		painelBotoes = new JPanel (new FlowLayout(FlowLayout.CENTER));
		painelUsuario.setBackground(new Color(133, 221, 222));
		painelSenha.setBackground(new Color(133, 221, 222));
		painelBotoes.setBackground(new Color(133, 221, 222));
		TratamentoJanelaPrincipal manipulador = new TratamentoJanelaPrincipal();
		botaoCriar.addActionListener(manipulador);
		botaoCriar.setMnemonic(KeyEvent.VK_C);
		botaoSair.setMnemonic(KeyEvent.VK_S);
		botaoSair.addActionListener(manipulador);
		botaoLogar.addActionListener(manipulador);

		//painelCriar.add(botaoCriar);
		painelUsuario.add(labelLogin);
		painelUsuario.add(fieldUser);
		painelSenha.add(labelSenha);
		painelSenha.add(fieldSenha);

		painelBotoes.add(botaoLogar);
		painelBotoes.add(botaoSair);
		Container areaConteudo = getContentPane();
		areaConteudo.setLayout(new BorderLayout());
		areaConteudo.setBackground(new Color(133, 221, 222));
	
		areaConteudo.add(painelUsuario, BorderLayout.NORTH);
		areaConteudo.add(painelSenha, BorderLayout.CENTER);
		areaConteudo.add(painelBotoes, BorderLayout.SOUTH);
	

	}

	class TratamentoJanelaPrincipal implements ActionListener {
		
		public void actionPerformed(ActionEvent e) {

			if (e.getSource() == botaoCriar) {

				try {
					@SuppressWarnings("unused")
					CCadastroConta cadastro = new CCadastroConta();
				} catch (SQLException e1) {
					
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					
					e1.printStackTrace();
				}

			}

			if (e.getSource() == botaoLogar) {

				String usuario = fieldUser.getText();
				String senha = fieldSenha.getText();
				fieldUser.setText("");
				fieldSenha.setText("");
				
				fieldUser.requestFocus();

				try {

					boolean logou = Verifica(usuario, senha);

					if (logou) {
						CUsuario chama = new CUsuario(usuario);
						chama.addWindowListener(new WindowAdapter() {

							public void windowClosing(WindowEvent e) {

								System.exit(0);
							}
						});
						dispose();

					}

				} catch (SQLException e1) {
				
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					
					e1.printStackTrace();
				}

			}

			if (e.getSource() == botaoSair) {
				int opcao;
				opcao = JOptionPane.showConfirmDialog(null,
						"Deseja mesmo fechar a janela?", "Fechar",
						JOptionPane.YES_NO_OPTION);
				if (opcao == JOptionPane.YES_OPTION)
					System.exit(0);
			}

		}

	}

	public boolean Verifica(String usuario, String senha) throws SQLException,
			ClassNotFoundException {

		boolean resultado;

		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection conn = DriverManager.getConnection(
				"jdbc:oracle:thin:@192.168.61.1:1521:XE", "andre", "senha");
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery("SELECT LOGIN, SENHA FROM USUARIO");

		Boolean ai1 = false;

		while (rs.next()) {

			if (rs.getString("login").equals(usuario)
					&& rs.getString("senha").equals(senha)) {

				ai1 = true;

			}

		}
		if (ai1 == true) {

			resultado = true;

		} else {
			JOptionPane
					.showMessageDialog(null,
							"Falha no logon, verifique usuario e senha e tente novamente.");
			resultado = false;
		}
		stmt.close();

		return resultado;

	}

	public static void main(String[] args) throws SQLException,
			ClassNotFoundException {

		CJanelaPrincipal abre = new CJanelaPrincipal();

		abre.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {

				System.exit(0);
			}
		});

	}
}

[ ] ’ s

Repare das linhas 34 até 53: bagunçado não?

E das linhas 55 até 92: incompreensível. Algum ser humano dotado de capacidades normais consegue entender algo?

Agora imagine: você faz seu código muito bonito no NetBeans e precisa alterar a posição de um botão. Mas no lugar onde você fará isso, não tem o NetBeans. E agora?

Nada contra (na verdade um pouco contra sim), mas porque não usa o Eclipse. Você pode fazer tudo na raça. Mas se não quiser, tudo bem…

Pode usar um dos muitos plugins que fazem trabalho semelhante ao drag and drop do NetBeans, mas de maneira “limpa”. É o Visual Editor.

Se quiser, baixe o Eclipse e o Visual Editor. Recomendo.

Marco,

Realmente fica tudo muito confuso. Por isso mostrei meu codigo feito em Eclipse, ainda que meio poluido para mim é bem mais facil a leitura.
Passei a utilizar o NetBeans por curiosidade, justamente pela facilidade em criação de frames. Poucos cliques e esta feito.

Estava atras de um plugin para o Eclipse que tivesse funcionalidade parecida, vou instalar este que voce disse e ver como funciona. Velho e bom Eclipse de guerra!

Obrigado!
Abraços