JavaFX TableView与CSV同步问题:增删改未写入CSV及编辑实现求助
Hey Nick, let's tackle your two main issues step by step—syncing TableView changes to your CSV file and implementing the edit functionality with a new scene. I'll break this down into actionable code changes and explanations.
1. First: Ensure Your Gebruiker Class is Fully Implemented
The PropertyValueFactory and edit functionality rely on proper getters and setters. Here's the complete class you need:
public class Gebruiker { private String voornaam; private String achternaam; public Gebruiker(String voornaam, String achternaam) { this.voornaam = voornaam; this.achternaam = achternaam; } // Getters for TableView column binding public String getVoornaam() { return voornaam; } public String getAchternaam() { return achternaam; } // Setters for edit functionality public void setVoornaam(String voornaam) { this.voornaam = voornaam; } public void setAchternaam(String achternaam) { this.achternaam = achternaam; } }
2. Add CSV Sync Logic (Read/Write)
Right now, your app loads data but doesn't save changes back to the CSV. Let's add two helper methods for this.
2.1 Load CSV Data on App Startup
Add this method to load existing users from your CSV into the dataList:
private void loadCsvData() { String csvPath = "gebruikers.csv"; // Replace with your actual file path String csvDelimiter = ","; try (BufferedReader reader = new BufferedReader(new FileReader(csvPath))) { // Skip header row if your CSV has one (uncomment below) // reader.readLine(); String line; while ((line = reader.readLine()) != null) { String[] userData = line.split(csvDelimiter); if (userData.length == 2) { dataList.add(new Gebruiker(userData[0].trim(), userData[1].trim())); } } } catch (FileNotFoundException e) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "CSV file not found!", e); } catch (IOException e) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Error reading CSV!", e); } }
Call this method in your start() right after initializing the table:
// After table.setItems(dataList) and adding columns loadCsvData();
2.2 Write Changes Back to CSV
Add this method to save the dataList to CSV whenever you add/edit/delete a user:
private void writeCsvData() { String csvPath = "gebruikers.csv"; // Same path as load method try (PrintWriter writer = new PrintWriter(new FileWriter(csvPath))) { // Optional: Write header row // writer.println("Voornaam,Achternaam"); for (Gebruiker user : dataList) { writer.println(user.getVoornaam() + "," + user.getAchternaam()); } } catch (IOException e) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Error writing to CSV!", e); } }
3. Fix the "Add" Functionality to Sync with CSV
Complete your saveButtonAddClicked() method to add the user to the list AND save to CSV:
private void saveButtonAddClicked() { String voornaam = voornaamInput.getText().trim(); String achternaam = achternaamInput.getText().trim(); if (!voornaam.isEmpty() && !achternaam.isEmpty()) { dataList.add(new Gebruiker(voornaam, achternaam)); writeCsvData(); // Sync changes to CSV ((Stage) voornaamInput.getScene().getWindow()).close(); // Close the add window } else { Alert errorAlert = new Alert(Alert.AlertType.ERROR); errorAlert.setTitle("Fout"); errorAlert.setContentText("Voer zowel een voornaam als achternaam in!"); errorAlert.showAndWait(); } }
4. Implement the "Edit" Functionality
First, add an edit button to your main button bar:
Button editButton = new Button("Bewerken"); editButton.setOnAction(e -> openEditWindow());
Then add the openEditWindow() method to handle the edit scene and update logic:
private void openEditWindow() { Gebruiker selectedUser = table.getSelectionModel().getSelectedItem(); if (selectedUser == null) { Alert warningAlert = new Alert(Alert.AlertType.WARNING); warningAlert.setTitle("Waarschuwing"); warningAlert.setContentText("Selecteer eerst een gebruiker om te bewerken!"); warningAlert.showAndWait(); return; } // Build the edit window UI Label titleLabel = new Label("Bewerk gebruiker"); HBox titleLayout = new HBox(titleLabel); titleLayout.setPadding(new Insets(10)); TextField editVoornaam = new TextField(selectedUser.getVoornaam()); editVoornaam.setPromptText("Voornaam"); TextField editAchternaam = new TextField(selectedUser.getAchternaam()); editAchternaam.setPromptText("Achternaam"); VBox inputLayout = new VBox(10, editVoornaam, editAchternaam); inputLayout.setPadding(new Insets(10)); // Save button logic Button saveEditBtn = new Button("Opslaan"); saveEditBtn.setOnAction(e -> { String newVoornaam = editVoornaam.getText().trim(); String newAchternaam = editAchternaam.getText().trim(); if (!newVoornaam.isEmpty() && !newAchternaam.isEmpty()) { selectedUser.setVoornaam(newVoornaam); selectedUser.setAchternaam(newAchternaam); table.refresh(); // Update TableView display writeCsvData(); // Sync changes to CSV ((Stage) saveEditBtn.getScene().getWindow()).close(); } else { Alert errorAlert = new Alert(Alert.AlertType.ERROR); errorAlert.setTitle("Fout"); errorAlert.setContentText("Voer zowel een voornaam als achternaam in!"); errorAlert.showAndWait(); } }); Button cancelBtn = new Button("Annuleren"); cancelBtn.setOnAction(e -> ((Stage) cancelBtn.getScene().getWindow()).close()); HBox buttonLayout = new HBox(10, saveEditBtn, cancelBtn); buttonLayout.setPadding(new Insets(10)); buttonLayout.setAlignment(Pos.CENTER); // Assemble the scene BorderPane editPane = new BorderPane(); editPane.setTop(titleLayout); editPane.setCenter(inputLayout); editPane.setBottom(buttonLayout); Scene editScene = new Scene(editPane, 600, 400); Stage editWindow = new Stage(); editWindow.setTitle("JavaFX - Bewerken"); editWindow.setScene(editScene); editWindow.initModality(Modality.WINDOW_MODAL); editWindow.initOwner(window); editWindow.showAndWait(); }
5. Fix the "Delete" Functionality to Sync with CSV
Update your delete button logic to save changes to CSV after removing a user:
Button deleteButton = new Button("Verwijder"); deleteButton.setOnAction(e -> { Gebruiker selectedUser = table.getSelectionModel().getSelectedItem(); if (selectedUser != null) { dataList.remove(selectedUser); writeCsvData(); // Sync deletion to CSV } else { Alert warningAlert = new Alert(Alert.AlertType.WARNING); warningAlert.setTitle("Waarschuwing"); warningAlert.setContentText("Selecteer eerst een gebruiker om te verwijderen!"); warningAlert.showAndWait(); } });
Don't forget to add this button to your main button layout (alongside "Toevoegen" and "Bewerken").
Quick Notes
- Ensure your CSV file is in the correct path relative to your app, or use an absolute path if needed
- If the CSV file doesn't exist yet, the
writeCsvData()method will create it automatically on first save - For a more polished experience, you could use JavaFX
StringPropertyin theGebruikerclass instead of plain strings—this would let the TableView auto-update without callingtable.refresh()
内容的提问来源于stack exchange,提问作者Nick van Bruggen




