在数据模型发生更改时更新 JTable

Update JTable upon a change in the data model

提问人:gregorsa 提问时间:11/12/2023 最后编辑:gregorsa 更新时间:11/12/2023 访问量:80

问:

我有一个更新用户数据的 JDialog,一旦我单击更新按钮,它就会验证数据,向我创建的端点发出 PUT 请求,并更新数据库中的用户数据。到目前为止,一切都很好

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {                                              
        URL url;
        if (validaDatos()) {
            try {

                Object idUsuario = recuperaPersona.get("id");
                url = new URL("http://localhost:8080/api/v1/usuario/" + idUsuario);

                //Preparar la información a enviar
                Map<String, Object> params = new LinkedHashMap<>();
                params.put("nombre", txtNombre.getText());
                params.put("primerApellido", txtPrimerApellido.getText());
                params.put("segundoApellido", txtSegundoApellido.getText());
                params.put("calle", txtCalle.getText());
                params.put("ciudad", txtCiudad.getText());
                params.put("codigoPostal", txtCodigoPostal.getText());
                params.put("fechaAlta", sdf.format(dchFechaAlta.getDate()));
                params.put("fechaNacimiento", sdf.format(dchFechaNacimiento.getDate()));
                if (ValidadorFormulario.validarDNI(txtDni.getText())) {
                    params.put("dni", txtDni.getText());
                } else {
                    JOptionPane.showMessageDialog(null, "El DNI no es correcto");
                }
                params.put("correoElectronico", txtCorreoElectronico.getText());
                params.put("telefono", txtTelefono.getText());
                params.put("fotoUsuario", rutaDeLaFoto);

                String jsonData = gson.toJson(params);
                System.out.println(jsonData);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("PUT");
                conn.setRequestProperty("Content-Type", "application/json");

                conn.setDoOutput(true);
                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = jsonData.getBytes("utf-8");
                    os.write(input, 0, input.length);
                }
                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    JOptionPane.showMessageDialog(null, "Paciente actualizado correctamente");
                    
                    
                    consumoApiVerPacientes.fireTableDataChanged();
                    
                    dispose();
                    
                }
                
                
                
                

            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

完成此操作后,我使用 fireTableDataChanged() 方法更新数据模型,以便更新此 JDialog 的父 Frame 中的表。问题在于数据模型不会以这种方式更新,从而使表保持不变且未更新。

这是我的数据模型:

public class ConsumoApiVerPacientes extends AbstractTableModel{
    private StringBuilder informationString;
    private JSONArray jSONArray;
    JSONObject objetoJson;

    private final String[] nombresColumnas = {"Nombre", "Primer Apellido", "Segundo Apellido", "DNI","Fecha de Nacimiento"};

    public ConsumoApiVerPacientes() {
        try {
            URL url = new URL("http://localhost:8080/api/v1/usuarios/todos");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("Ocurrió un error: " + responseCode);
            } else {
                informationString = new StringBuilder();
                Scanner scanner = new Scanner(url.openStream());

                while (scanner.hasNext()) {
                    informationString.append(scanner.nextLine());
                }
                scanner.close();

                jSONArray = new JSONArray(informationString.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getRowCount() {
        return jSONArray.length();
    }

    @Override
    public int getColumnCount() {
        return 5;
    }

    @Override
    public Object getValueAt(int fila, int columna) {
         objetoJson = jSONArray.getJSONObject(fila);
        switch (columna) {
            case 0:
                return objetoJson.get("nombre");
            case 1:
                return objetoJson.get("primerApellido");
            case 2:
                return objetoJson.get("segundoApellido");
            case 3:
                return objetoJson.get("dni");
            case 4:
                return objetoJson.get("fechaNacimiento");
           
        }
        return null;
    }

    @Override
    public String getColumnName(int i) {
        return nombresColumnas[i];
    }
    
    public JSONObject recuperaPersona(int indiceTabla){
        return jSONArray.getJSONObject(indiceTabla);
        
        
    }
    
  
}

我认为,问题在于 fireTableDataChanged() 不会从 JDialog 传播到父元素。因此,我将不胜感激这方面的帮助

下面是表格所在的框架:

public class VerPacienteParaActualizar extends javax.swing.JFrame {

    public ConsumoApiVerPacientes consumoApiVerPacientes; 
    

    VerPacienteCompletoParaActualizar verPacienteCompletoParaActualizar;

    public VerPacienteParaActualizar() {
        initComponents();
        tblVerPacientes.getTableHeader().setFont(new Font("Segoe UI", Font.BOLD, 12));
        tblVerPacientes.getTableHeader().setOpaque(false);
        tblVerPacientes.getTableHeader().setBackground(new Color(0, 152, 152));
        consumoApiVerPacientes = new ConsumoApiVerPacientes();
        tblVerPacientes.setModel(consumoApiVerPacientes);
        

        traeListaTodosLosPacientes();
        
        
    }

    public void traeListaTodosLosPacientes() {
        URL url;
        try {
            url = new URL("http://localhost:8080/api/v1/usuarios/todos");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("Ocurró un error: " + responseCode);
            } else {
                StringBuilder informationString = new StringBuilder();
                Scanner scanner = new Scanner(url.openStream());

                while (scanner.hasNext()) {
                    informationString.append(scanner.nextLine());
                }
                scanner.close();

                JSONArray jSONArray = new JSONArray(informationString.toString());

            }
        } catch (IOException | RuntimeException e) {
            e.printStackTrace();
        }

    }
    public JTable traeTabla(){
        return tblVerPacientes;
    }

private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        switch ((String) cmbParametro.getSelectedItem()) {
            case "Primer Apellido":
                ConsumoApiVerPacientesPorPrimerApellido consumoApiVerPacientesPorPrimerApellido = new ConsumoApiVerPacientesPorPrimerApellido(txtCriterio.getText());
                tblVerPacientes.setModel(consumoApiVerPacientesPorPrimerApellido);
                buscaPacientePorPrimerApellido(txtCriterio.getText());
                consumoApiVerPacientesPorPrimerApellido.fireTableDataChanged();
                break;
            case "Nombre":
                ConsumoApiVerPacientesPorNombre consumoApiVerPacientesPorNombre = new ConsumoApiVerPacientesPorNombre((txtCriterio.getText()));
                tblVerPacientes.setModel(consumoApiVerPacientesPorNombre);
                buscaPacientePorNombre(txtCriterio.getText());
                consumoApiVerPacientesPorNombre.fireTableDataChanged();
                break;
            case "Segundo Apellido":
                ConsumoApiVerPacientesPorSegundoApellido consumoApiVerPacientesPorSegundoApellido = new ConsumoApiVerPacientesPorSegundoApellido(txtCriterio.getText());
                tblVerPacientes.setModel(consumoApiVerPacientesPorSegundoApellido);
                buscaPacientePorSegundoApellido(txtCriterio.getText());
                consumoApiVerPacientesPorSegundoApellido.fireTableDataChanged();
                break;
            case "Todos":
                tblVerPacientes.setModel(consumoApiVerPacientes);
                consumoApiVerPacientes.fireTableDataChanged();

                break;

            case "DNI":
                ConsumoApiVerPacientesPorDni consumoApiVerPacientesPorDni = new ConsumoApiVerPacientesPorDni(txtCriterio.getText());
                tblVerPacientes.setModel(consumoApiVerPacientesPorDni);
                buscaPacientePorDni(txtCriterio.getText());
                consumoApiVerPacientesPorDni.fireTableDataChanged();
                break;

        }


    }                                         
 
    private void tblVerPacientesMouseClicked(java.awt.event.MouseEvent evt) {                                             

        Point puntoClickeado = evt.getPoint();
        int filaDelPuntoClickeado = tblVerPacientes.rowAtPoint(puntoClickeado);
        int filaSeleccionada = tblVerPacientes.getSelectedRow();
        switch ((String) cmbParametro.getSelectedItem()) {
            case "Todos":
                verPacienteCompletoParaActualizar = new VerPacienteCompletoParaActualizar(this, true,consumoApiVerPacientes, filaDelPuntoClickeado);
                System.out.println("2-"+consumoApiVerPacientes.hashCode());
                verPacienteCompletoParaActualizar.setVisible(true);

                break;
            case "Segundo Apellido":
                ConsumoApiVerPacientesPorSegundoApellido consumoApiVerPacientesPorSegundoApellido = new ConsumoApiVerPacientesPorSegundoApellido(txtCriterio.getText());
                verPacienteCompletoParaActualizar = new VerPacienteCompletoParaActualizar(this, true, consumoApiVerPacientesPorSegundoApellido, filaDelPuntoClickeado);
                verPacienteCompletoParaActualizar.setVisible(true);
                break;
            case "Nombre":
                ConsumoApiVerPacientesPorNombre consumoApiVerPacientesPorNombre = new ConsumoApiVerPacientesPorNombre(txtCriterio.getText());
                verPacienteCompletoParaActualizar = new VerPacienteCompletoParaActualizar(this, true, consumoApiVerPacientesPorNombre, filaDelPuntoClickeado);
                verPacienteCompletoParaActualizar.setVisible(true);
                break;
            case "Primer Apellido":
                ConsumoApiVerPacientesPorPrimerApellido consumoApiVerPacientesPorPrimerApellido = new ConsumoApiVerPacientesPorPrimerApellido(txtCriterio.getText());
                verPacienteCompletoParaActualizar = new VerPacienteCompletoParaActualizar(this, true, consumoApiVerPacientesPorPrimerApellido, filaDelPuntoClickeado);
                verPacienteCompletoParaActualizar.setVisible(true);
                break;
            case "DNI":
                ConsumoApiVerPacientesPorDni consumoApiVerPacientesPorDni = new ConsumoApiVerPacientesPorDni(txtCriterio.getText());
                verPacienteCompletoParaActualizar = new VerPacienteCompletoParaActualizar(this, true, consumoApiVerPacientesPorDni, filaDelPuntoClickeado);
                verPacienteCompletoParaActualizar.setVisible(true);
                break;
        }

    }                 
java swing jtable

评论


答: 暂无答案