Reputation: 11
I'm currently trying to write a simple CRUD using Java. I've made a separate class to Connect to mySQL Database. I then created a JFrame
and I used the extends to bind that class to my JFrame
. I also created a JDialog
called "FormCadastro", that opens when the user choose some function in a JMenu
, at this point everything is working fine, the JDialog
appears from JFrame
but the problem is that the JDialog
class is not seeing my "ConnectDataBase" class, and I need to access it when the user clicks "Register" to send data from JDialog TextFields
to my database.
JDialog Class
JButton OkBtn = new JButton("Cadastrar");
OkBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String query = "INSERT INTO dados_pessoais(Codigo, Nome, SobreNome, Endereco, Numero, Bairro, Cidade, UF, Email, Celular, Telefone) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(query);
//JDialog does not see "con" variable and PreparedStatement class even if i import it using import Classes.ConnectDataBase,
}
}
If I use extends ConnectDataBase
in the place of JDialog
at
public class FormCadastro extends JDialog
I get a lot of errors, so I don't know what to do to access that DataBase class in my JDialog.
ConnectDataBase Class
public class ConnectDataBase
{
private Connection con = null;
private ResultSet rs = null;
public void ConnectDataBase() throws ClassNotFoundException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
this.con = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuarios", "root", "admin");
JOptionPane.showMessageDialog(null, "Conexão com o Banco de Dados bem sucedida");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Erro ao tentar conectar ao Banco de Dados", "Erro de Conexão", JOptionPane.ERROR_MESSAGE);
}
}
}
Upvotes: 0
Views: 47
Reputation: 285405
If you want your JDialog-extending class to use the functionality of the ConnectDataBase, then you have to pass a viable ConnectDataBase into the JDialog class, perhaps in its constructor or via a setter method. Using imports does not magically confer ability. You need to use composition.
e.g.,
public class FormCadastro extends JDialog {
private ConnectDataBase connectDataBase;
public FormCadastro(ConnectDataBase connectDataBase) {
this.connectDataBase = connectDataBase;
JButton OkBtn = new JButton("Cadastrar");
OkBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO dados_pessoais (Codigo,Nome,SobreNome,Endereco,Numero,Bairro,Cidade,UF,Email,Celular,Telefone) VALUES ( ?,?,?,?,?,?,?,?,?,?,?)";
// use public methods of your connectDataBase object here
}
});
}
}
Upvotes: 1