如何在Java其他类中获取jTextField或jFormattedTextField的数据
问题根因
报错的核心原因是Modos类作为独立的后端业务类,没有持有GUI类中jFormattedTextFieldCPF组件的引用,无法直接访问GUI层的组件对象,所以触发cannot find symbol错误。
解决方案
推荐使用参数传值的方案实现,完全符合分层解耦的开发规范,后端类不需要依赖任何GUI组件:
步骤1:修改GUI层按钮事件代码
在GUI层先拿到输入框的内容,直接把值传给后端Modos类的方法,还可以提前做空校验拦截无效请求:
private void jButtonExcluirActionPerformed(java.awt.event.ActionEvent evt) { MODO = 1;// 传递按钮需要执行的操作标识 // 提前在GUI层获取CPF输入值并做空校验 String cpfInput = jFormattedTextFieldCPF.getText().trim(); if (cpfInput.isEmpty()) { JOptionPane.showMessageDialog(null, "Por favor completar o campo CPF"); return; } // 将CPF值作为参数传给后端方法 funcao.funcoes(MODO, cpfInput); }
步骤2:修改Modos类的funcoes方法
调整方法入参接收前端传递的CPF值,直接使用该值操作数据库即可:
// 新增入参接收GUI层传递的CPF值 public void funcoes(int MODO, String cpf) { if (MODO == 1){ PreparedStatement stm; try { stm = conecta.conn.prepareStatement("delete from cad_pessoa where cad_cpf=?"); // 直接使用传过来的CPF值 stm.setString(1, cpf); stm.execute(); conecta.conn.commit(); JOptionPane.showMessageDialog(null, "Excluído!"); } catch (SQLException ex) { Logger.getLogger(Pessoa.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Erro:01\n" + ex.getMessage()); // 异常时才需要回滚事务 try { conecta.conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } } } // 后续新增、编辑等其他操作需要更多参数时,可以继续扩展入参 }
扩展优化建议
如果后续新增、编辑操作需要传递姓名、年龄、生日等多个字段,建议封装一个POJO实体类传递参数,代码更整洁易维护:
// 封装实体类存储用户信息 public class Pessoa { private String cpf; private String nome; private Integer idade; private String dataNascimento; private String apelido; // 按需添加构造方法、getter、setter方法 }
调用方法时直接将GUI层所有输入框的内容封装为Pessoa对象传给funcoes方法即可,不需要逐个传递多个参数。
内容的提问来源于stack exchange,提问作者Luís Felipe Ambrozin
相关产品推荐
相关产品推荐

