Java Swing: Removing and Exporting Candidate Data to a Text File
Removing and Exporting Candidate Data in Java Swing
The following methods handle the removal of a candidate record and the export of candidate data to a text file.
Removing a Candidate
btnRemoverMousePressed removes the candidate whose CPF is shown in the txtCPF field, then displays the first remaining candidate, if any.
private void btnRemoverMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (this.dados.containsKey(txtCPF.getText())) {
this.dados.remove(txtCPF.getText());
this.indices.remove(txtCPF.getText());
}
if (this.indices.size() > 0) { // Check whether any records remain
String cpfProx = this.indices.get(0); // Return to the first record
Candidato c = this.dados.get(cpfProx);
this.preencherCampos(c);
}
}Exporting Candidate Data
btnExportMousePressed writes the data of the current candidate to a file named after the candidate's CPF. The export only runs when no new record is being inserted.
private void btnExportMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
FileWriter arq;
if (!this.novo) { // Ensure no insertion is in progress
try {
arq = new FileWriter(txtCPF.getText() + ".txt"); // File name uses the candidate's CPF
PrintWriter gravarArq = new PrintWriter(arq);
// Write the candidate's data to the file
Candidato c = this.dados.get(txtCPF.getText());
gravarArq.printf("Candidato: " + c.getNome());
gravarArq.printf("\t\tCPF: " + c.getCpf());
gravarArq.printf("\nNascimento: " + c.getNascimento());
gravarArq.printf("\t\tIdade: " + String.valueOf(c.getIdade()));
gravarArq.printf("\nEscolaridade: " + c.getListaEscolaridade()[c.getEscolaridade()]);
gravarArq.printf("\nInstituição: " + c.getInstituicao());
if (c.getEscolaridade() == 2)
gravarArq.printf("\nCurso: " + c.getCurso());
gravarArq.printf("\nCargo Pretendido: " + c.getCargo());
gravarArq.printf("\t\tSalário Pretendido: " + String.valueOf(c.getSalario()));
arq.close();
JOptionPane.showMessageDialog(null, "Arquivo exportado com sucesso!");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Problemas na escrita do arquivo");
}
}
}Important Notes
- The
PrintWriteris only flushed when the file is closed. Closingarqbefore thePrintWriteris also safer, so consider callinggravarArq.close()instead. - Use
printlninstead ofprintfwhen the text contains no format specifiers, sinceprintftreats%characters as formatting directives.