我目前正在尝试使用Java编写一个简单的CRUD。我做了一个单独的类来连接到mySQL数据库。然后,我创建了一个JFrame,并使用扩展将该类绑定到我的JFrame。我还创建了一个名为“ FormCadastro”的JDialog,当用户在JMenu中选择某些功能时打开,此时一切正常,JDialog从JFrame出现,但问题是类没有看到我的“ ConnectDataBase”类,并且当用户单击“注册”以将数据从JDialog发送到我的数据库时,我需要访问它。JDialog类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, }}如果我使用JDialog TextFields代替extends ConnectDataBasepublic class FormCadastro extends JDialog我收到很多错误,所以我不知道该怎么做才能访问该数据库我的JDialog中的类。ConnectDataBase类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); } }} (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 如果希望JDialog扩展类使用ConnectDataBase的功能,则必须将可行的ConnectDataBase传递到JDialog类中,也许在其构造函数中或通过setter方法。使用导入并不能神奇地赋予能力。您需要使用合成。例如。,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 } }); }} (adsbygoogle = window.adsbygoogle || []).push({}); 09-26 05:56