Duvidas com Conexão ao BD

28 respostas
hacebe

Pessoal…

Estou desenvolvendo uma aplicacao…
Sou iniciante e por enquanto estou aprendendo java e fazendo alguns testes!

Eu consegui criar uma conexão com o banco de dados e fazer uma pesquisa simples.

A minha duvida é como posso utilizar essa conexão em outros formulários e classes sem precisar reescrever as linhas de conexão?

utilizo isso aqui

String url = “jdbc:mysql://localhost:3306/geomap”;
Connection conn = DriverManager.getConnection(url,“root”,“geomap”);

Obrigado pela atençao pessoal

28 Respostas

G

Bom dia,
Crie uma classe que possua um método que lhe retorne a conexão pronta com o banco… :lol:

Tente pesquisar sobre…qualquer dúvida post suas dúvidas aqui!!

[]´s

hudson.negao

cara da uma procurada por design patterns
mais precisamente o Singleton
pode te ajudar a resolver isso!

M

Cria uma classe abstrata e extende dela suas classes de acesso ao banco. É aconselhavel utilizar pool de conexao, para não sobrecarregar o banco.

colored

Tipo como ja disseram cria uma classe com um metodo q retorna a conexao oh um exemplo meu…

public static Connection CriarConexao() throws SQLException{ try{ Class.forName("net.sourceforge.jtds.jdbc.Driver"); Connection c; c = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost/Northwind","",""); return c; } catch (ClassNotFoundException ex) { throw new SQLException(ex.getMessage()); }

K

Você pode chamar essa conexão na primeira classe que é chamada no programa. Por exemplo:

public class BD

{

public static Connection getConnection(String url, String database, String user, String password)

{

//código de conexão

return <connexão>
}

  public static <tipo de retorno> <método para o qual quer conectar com a base>(Connection c, <parâmetros>)
 {
       //código para a comunicação de acordo com o método
 }
 .....

}

public class teste1

{

public void teste()

{

Connection c = BD.getConnection(url, database, user, password);

//usa a conexão em outro método da classe BD

}

}
public class teste2

{

public void teste()

{

Connection c = BD.getConnection(url, database, user, password);

//usa a conexão em outro método da classe BD

}

}

Entendeu?

colored

Depois na Hora de pega a conexao na sua classe.

private Connection c;

public ClienteDAO() throws SQLException {
  c = NomeDaClasse.CriarConexao();
}
K

Isso mesmo. Aí, vc usa essa conexão em todos os métodos que forem fazer comunicação com a base.

hacebe

Pessoal… nao entendi mto bem nao…

to aprendendo agora… entao isso pra mim é grego!

eu fiz parcialmente o que vocês falaram ai.

Criei uma classe.
Importei ela em outro local

mas nao consigo utilizar ainda!
obrigado pela ajuda !

K

Como vc fez isso?

hacebe

no ConnDB.java:

import java.sql.*;
/**
 *
 * @author Geomap
 */
public class ConnDB {
    //public static void main(String []args){
        
        public Connection getConnection() {
        Connection Conn = null;
        // Carregando o JDBC Driver
        String vdriverName = "com.mysql.jdbc.Driver";//não esquecer de adicionar a biblioteca do mySQL
        try {
            Class.forName(vdriverName);
        } catch (ClassNotFoundException ex) {
            return null;
        }
        try {
            Conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/3306", "root", "geomap");
            return Conn;
        } catch (SQLException ex) {
            return null;
        }
    }

        
    

}
No GeomapView.java
/*
 * GeomapView.java
 */

package geomap;

import java.sql.*;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import Geomap.*;

/**
 * The application's main frame.
 */
public class GeomapView extends FrameView {

    public GeomapView(SingleFrameApplication app) {
        super(app);
        
        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = GeomapApp.getApplication().getMainFrame();
            aboutBox = new GeomapAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        GeomapApp.getApplication().show(aboutBox);
    }
    
    @Action
    public void enviaForm(){
      String usuario = txtUsuario.getText();
      Connection conexao;
      Statement stmt;
  
    String correta = "teste";
    
   

   String digitada = new String(txtSenha.getPassword());

   if(correta.equals(digitada)){
      System.out.println("Correta");
   }else{
      System.out.println("inCorreta");
   }
            
    }
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        btnEnviar = new javax.swing.JButton();
        txtUsuario = new javax.swing.JTextField();
        txtSenha = new javax.swing.JPasswordField();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(geomap.GeomapApp.class).getContext().getActionMap(GeomapView.class, this);
        btnEnviar.setAction(actionMap.get("enviaForm")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(geomap.GeomapApp.class).getContext().getResourceMap(GeomapView.class);
        btnEnviar.setText(resourceMap.getString("btnEntrar.text")); // NOI18N
        btnEnviar.setName("btnEntrar"); // NOI18N

        txtUsuario.setText(resourceMap.getString("txtUsuario.text")); // NOI18N
        txtUsuario.setName("txtUsuario"); // NOI18N

        txtSenha.setText(resourceMap.getString("txtSenha.text")); // NOI18N
        txtSenha.setName("txtSenha"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap(263, Short.MAX_VALUE)
                        .addComponent(btnEnviar))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                        .addGap(129, 129, 129)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE))))
                .addGap(102, 102, 102))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addGap(111, 111, 111)
                .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addComponent(btnEnviar)
                .addGap(59, 59, 59))
        );

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 226, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setStatusBar(statusPanel);
    }// </editor-fold>

    // Variables declaration - do not modify
    private javax.swing.JButton btnEnviar;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JPasswordField txtSenha;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}

:? espero nao estar tao errado assim!

Obrigado!

K
1. import java.sql.*;  
   2. /** 
   3. * 
   4. * @author Geomap 
   5. */  
   6. public class ConnDB {  
   7.     //public static void main(String []args){  
   8.           
   9.         public Connection getConnection() {  
  10.         Connection Conn = null;  
  11.         // Carregando o JDBC Driver  
  12.         String vdriverName = "com.mysql.jdbc.Driver";//não esquecer de adicionar a biblioteca do mySQL  
  13.         try {  
  14.             Class.forName(vdriverName);  
  15.         } catch (ClassNotFoundException ex) {  
  16.             return null;  
  17.         }  
  18.         try {  
  19.             Conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/3306", "root", "geomap");  
  20.             return Conn;  
  21.         } catch (SQLException ex) {  
  22.             return null;  
  23.         }  
  24.     }  
  25.   
  26.           
  27.       
  28.   
  29. }

Nesse código, vc pode fazer assim:

import java.sql.*;  
   /** 
   * 
   * @author Geomap 
   */  
   public class ConnDB {  
       //public static void main(String []args){  
           
         public Connection getConnection() {  
           Connection Conn = null;  
          // Carregando o JDBC Driver  
           String vdriverName = "com.mysql.jdbc.Driver";//não esquecer de adicionar a biblioteca do mySQL  
          try {  
                   Class.forName(vdriverName);  
                    Conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/3306", "root", "geomap");  
              return Conn;  
           } catch (Exception ex) {  
               return null;  
          }  
      }       
 }
hacebe

Funcionou…
Cara tu eh demais!

Um dia vou ser como tu!

Mto obrigado mesmo
valeu!

:wink:

hacebe

Opa... me precipitei...

Eu tenho duvidas aonde vou declarar as Statements e as Strings...

public void enviaForm(){
    
    
    
    String usuario;
    usuario =  txtUsuario.getText();
    Statement stmt = conexao.createStatement();

}

O netbeans diz:

unreported exception java.sql.SQLException; must be caught or be declared to be thrown

To ficando desesperado!
Obrigado!

K

Os statements vc declara na mesma classe que vc fez a conexão da base. Nessa classe, vc faz todos os métodos que usa statements… deixa aquela classe só para comunicação a banco de dados.

hacebe

Amigo... sei q to enxendo o saco...

mas ve se ta certo isso aqui

import java.sql.*;  
   /** 
   * 
   * @author Geomap 
   */  
   public class ConnDB {  
       //public static void main(String []args){  
         
         public Connection  getConnection() {  
           Connection Conn = null; 
           
          // Carregando o JDBC Driver  
           String vdriverName = "com.mysql.jdbc.Driver";//não esquecer de adicionar a biblioteca do mySQL  
          try {  
                   Class.forName(vdriverName);  
                    Conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/geomap", "root", "geomap");  
                    Statement stmt = Conn.createStatement();
              return Conn;
             
           } catch (Exception ex) {  
               return null;  
          }  
      }

se estiver, como faço pra pegar ele na outra classe?

desculpa mais uma vez.
e Obrigado!

K

Está certo, sim, mas deixa o stmt como variável privada da classe... assim:

# import java.sql.*;    
#    /**  
#    *  
#    * @author Geomap  
#    */    
#    public class ConnDB {    
            private Statement stmt;

#        //public static void main(String []args){    
#            
#          public Connection  getConnection() {    
#            Connection Conn = null;   
#              
#           // Carregando o JDBC Driver    
#            String vdriverName = "com.mysql.jdbc.Driver";//não esquecer de adicionar a biblioteca do mySQL    
#           try {    
#                    Class.forName(vdriverName);    
#                     Conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/geomap", "root", "geomap");    

#               return Conn;  
#                
#            } catch (Exception ex) {    
#                return null;    
#           }    
#       } 

public void comunicacao1(Connection c, <parâmetros>)
{
       stmt = c.createStatement();  
       //restante do código
}
hacebe

Amigo… mais uma vez aqui ¬¬’

Fiz tudo isso ai e mesmo erro

unreported exception java.sql.SQLException; must be caught or be declared to be thrown

Você testou o código?

Desculpa o encomodo ai tranquilo?

Abrr!

K

Testei naum… então faz isso:

public void comunicacao1(Connection c, <parâmetros>) throws SQLException

{

stmt = c.createStatement();

//restante do código

}

isso conserta o erro que deu! ^^

Gobain

Buenas!

O problema q vc teve ali é pq o createStatement tb lança uma SQLException, então vc precisa estar preparado pra ela. Como? Usando um bloco try { ... } catch(SQLException sqlep) { ... } por exemplo.

public static Connection pegarConexao(String driver, String url, String usr, String pwd) {
	Connection con = null;
	
	try {
		Class.forName(driver);
		
		con = DriverManager.getConnection(url,usr,pwd);
	} catch(ClassNotFoundException cnfep) {
		cnfep.printStackTrace();
	} catch(SQLException sqlep) {
		sqlep.printStackTrace();
	}
	
	return con;
}
public static Statement criarStatement(Connection con) throws SQLException {
	return con.createStatement();
}

public static Statement criarStatement(Connection con) {
	Statement stm = null;

	try {
		stm = con.createStatement();
	} catch(SQLException sqlep) {
		sqlep.printStackTrace();
	}

	return stm;
}
hacebe

ficou certo agora!

e agora… como faço a pesquisa no banco pela outra classe :?

tamo quase la!
obrigado!

K

É só chamar o método da classe que faz conexão ao banco e usá-la!

hacebe

Amigo… se nao for pedir muito… eu nao sei fazer isso… tem como dar uma luz?

Obrigado!

Gobain

O q mais específicamente vc quer fazer?
Pra fazer a pesquisa vc vai ter q conectar, criar um statement ou preparedStatement com a sua query e pegar a resposta em um resultSet, tratá-la e usar os dados da consulta.

Um exemplo bem tosco aqui pra vc fazer uma consulta, substituindo o Objeto pelos seus objetos e o atributo pelos atributos do seu objeto e a coluna respectiva no banco.

public static void executarQuery(Connection con, String query) throws SQLException {
		ResultSet rs = con.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE,
				ResultSet.CONCUR_UPDATABLE).executeQuery(query);
		
		Objeto obj = null;
		
		while(rs.next()) {
			obj = new Objeto();
			
			obj.setAtributo1(rs.getObject("atributo_1"));
			obj.setAtributo2(rs.getObject("atributo_2"));
			
			System.out.println(obj);
		}
		
		rs.close();
	}

Tá bem simples, mas acho q da pra ter uma idéia. :D

K

Sim sim!

em uma outra classe, faz o seguinte:

public class Teste
{
         public static void main(String args[])
         {
                 try
                 {
                       Connection c = BD.getConnection(<parâmetros>);
                       Statement stmt = BD.criarStatement(c);
                 }
                 catch(Exception e)
                 {
                        e.printStackTrace();
                 }
         }
}
hacebe

nada amigos!

Gobain

Como assim nada?
Vc tem que dizer o q quer fazer, como quer fazer… não da pra gente ir jogando conteúdo aleatóriamente…

hacebe

Olha o código ai...

CONNDB.JAVA

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

package geomap;
import java.util.*;
import java.sql.*;  
   /** 
   * 
   * @author Geomap 
   */  
   public class ConnDB {  
       //public static void main(String []args){  
         private Statement stmt;
         public Connection  getConnection() {  
             
           Connection Conn = null; 
           
           
          // Carregando o JDBC Driver  
           String vdriverName = "com.mysql.jdbc.Driver";//não esquecer de adicionar a biblioteca do mySQL  
          try {  
                   Class.forName(vdriverName);  
                    Conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/geomap", "root", "geomap");  
                   /* Statement stmt = Conn.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT * FROM TAB_USUARIOS");
                    while (rs.next()){
                        System.out.println(rs.getString("TU_NOME"));
                    }*/
              return Conn;
              
             
           } catch (Exception ex) {  
               return null;  
          }  
      }       
         public void comunicacao1(Connection c) throws SQLException  { 
            stmt = c.createStatement();    
         }
   }

GEOMAPVIEW.JAVA

/*
 * GeomapView.java
 */

package geomap;

import java.sql.*;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
//import Geomap.*;

/**
 * The application's main frame.
 */
public class GeomapView extends FrameView {
    Connection conexao;
    String usuario = null;

    public static void executarQuery(Connection con, String query) throws SQLException{
        ResultSet rs = con.createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE).executeQuery(query);
        Object obj = null;
        
        while(rs.next()){
            obj = new Object();
            System.out.println(":" + rs.getString("TU_NOME"));
        }
        rs.close();
    }
    public GeomapView(SingleFrameApplication app) {
        
        super(app);
       
        
        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = GeomapApp.getApplication().getMainFrame();
            aboutBox = new GeomapAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        GeomapApp.getApplication().show(aboutBox);
    }

    @Action
    public void enviaForm(){

          
            usuario =  txtUsuario.getText();
           // sql = new executarQuery();
            

            String correta = "teste";



           String digitada = new String(txtSenha.getPassword());

           if(correta.equals(digitada)){
              System.out.println("Correta");
           }else{
              System.out.println("inCorreta");
           }
            
    }
      
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        btnEnviar = new javax.swing.JButton();
        txtUsuario = new javax.swing.JTextField();
        txtSenha = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(geomap.GeomapApp.class).getContext().getActionMap(GeomapView.class, this);
        btnEnviar.setAction(actionMap.get("enviaForm")); // NOI18N
        btnEnviar.setName("btnEntrar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(geomap.GeomapApp.class).getContext().getResourceMap(GeomapView.class);
        txtUsuario.setText(resourceMap.getString("txtUsuario.text")); // NOI18N
        txtUsuario.setName("txtUsuario"); // NOI18N

        txtSenha.setText(resourceMap.getString("txtSenha.text")); // NOI18N
        txtSenha.setName("txtSenha"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnEnviar))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(93, 93, 93)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 159, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(mainPanelLayout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(txtSenha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                                    .addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE))))))
                .addGap(101, 101, 101))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEnviar)
                .addContainerGap(34, Short.MAX_VALUE))
        );

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 219, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setStatusBar(statusPanel);
    }// </editor-fold>

    // Variables declaration - do not modify
    private javax.swing.JButton btnEnviar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JPasswordField txtSenha;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}

Foi mal ai...

No arquivo ConnDB.java, ele cria a conexão com o mysql

Quero que no arquivo geomapview.java e os demais arquivos também tenham acesso a essa conexão, sem que seja necessario reescrever esse codigo!

é isso ai

VALEU

hacebe

Resolvi o problema…

Muito obrigado pessoal!

:wink:

Criado 9 de abril de 2008
Ultima resposta 10 de abr. de 2008
Respostas 28
Participantes 7