JavaFX获取选择框特定值及选中员工后填充文本框的实现
Alright, let's get this sorted so that when you pick an employee from your employeeList ChoiceBox, their details automatically populate the corresponding TextFields. Here's how to do it step by step:
Step 1: Fix the ChoiceBox Generic Type
First, update your employeeList declaration to use a generic type of Employees—this avoids messy casting later and makes the code safer:
@FXML private ChoiceBox<Employees> employeeList;
Step 2: Add a Selection Listener to the ChoiceBox
You need to listen for when the selected item in employeeList changes. The best place to set this up is in an initialize() method (FXML controllers can use this annotated method to run setup logic when the UI loads):
@FXML public void initialize() { // Add listener for selection changes employeeList.getSelectionModel().selectedItemProperty().addListener((obs, oldEmp, newEmp) -> { // Only update fields if a valid employee is selected if (newEmp != null) { name.setText(newEmp.getName()); age.setText(String.valueOf(newEmp.getAge())); // Convert int to String for TextField address.setText(newEmp.getAddress()); salary.setText(String.valueOf(newEmp.getSalary())); // Convert int to String for TextField } else { // Clear fields if no selection is made name.clear(); age.clear(); address.clear(); salary.clear(); } }); // Load all employees into the employeeList (replace with your existing logic if it's already working) loadAllEmployees(); }
Step 3: Clean Up Data Loading
We'll add a helper method to load all employees into the list, keeping the code organized and reusable:
private void loadAllEmployees() { try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/employees", "root", "ljubisa97")) { emp_collection = new ArrayList<>(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM employees.employee_db"); // Fetch all employees, not just ID 3 while (rs.next()) { Employees emp = new Employees( rs.getInt("emp_id"), rs.getString("name"), rs.getInt("age"), rs.getString("address"), rs.getInt("salary") ); emp_collection.add(emp); employeeList.getItems().add(emp); } } catch (SQLException ex) { System.out.println("Error loading employees: \n" + ex.getMessage()); } }
Full Modified Controller Code
Here's the complete updated controller with all changes included:
import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import java.sql.*; import java.util.ArrayList; import java.util.List; public class employeeController { @FXML private TextField name; @FXML private TextField age; @FXML private TextField address; @FXML private TextField salary; @FXML private TextField delete; @FXML private TextField selUp; @FXML private Button updateBtn; @FXML private ToggleButton eId; @FXML private ToggleButton eName; @FXML private ToggleButton select; @FXML private ToggleButton update; @FXML private ChoiceBox<Employees> employeeList; // Updated generic type @FXML private ChoiceBox<Employees> updateList; // Updated generic type @FXML private TextArea infoArea; @FXML private TextField newValue; List<Employees> emp_collection; ResultSet rs; ObservableList<String> empCol = FXCollections.<String>observableArrayList("ID", "Name", "Age", "Address", "Salary"); Employees emp; public employeeController() { } @FXML public void initialize() { // Setup selection listener for employeeList employeeList.getSelectionModel().selectedItemProperty().addListener((obs, oldEmp, newEmp) -> { if (newEmp != null) { name.setText(newEmp.getName()); age.setText(String.valueOf(newEmp.getAge())); address.setText(newEmp.getAddress()); salary.setText(String.valueOf(newEmp.getSalary())); } else { name.clear(); age.clear(); address.clear(); salary.clear(); } }); // Load all employees into the list on initialization loadAllEmployees(); } private void loadAllEmployees() { try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/employees", "root", "ljubisa97")) { emp_collection = new ArrayList<>(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM employees.employee_db"); while (rs.next()) { Employees emp = new Employees( rs.getInt("emp_id"), rs.getString("name"), rs.getInt("age"), rs.getString("address"), rs.getInt("salary") ); emp_collection.add(emp); employeeList.getItems().add(emp); } } catch (SQLException ex) { System.out.println("Error loading employees: \n" + ex.getMessage()); } } @FXML private void update() throws SQLException { if(!update.isSelected()){ updateList.setVisible(false); updateBtn.setVisible(false); } else if(update.isSelected()){ updateList.setVisible(true); updateBtn.setVisible(true); try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/employees", "root", "ljubisa97")) { emp_collection = new ArrayList<>(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM employees.employee_db"); updateList.getItems().clear(); // Clear old items to avoid duplicates while (rs.next()) { emp = new Employees(rs.getInt("emp_id"), rs.getString("name"), rs.getInt("age"), rs.getString("address"), rs.getInt("salary")); emp_collection.add(emp); updateList.getItems().add(emp); } } catch (SQLException ex) { System.out.println("Error in database connection: \n" + ex.getMessage()); } } } public static class Employees { private int id; private String name; private int age; private String address; private int salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Employees() { } public Employees(String name, int age, String address, int salary) { this.name = name; this.age = age; this.address = address; this.salary = salary; } public Employees(int id, String name, int age, String address, int salary) { this.id = id; this.name = name; this.age = age; this.address = address; this.salary = salary; } @Override public String toString() { return "ID: " + getId() + " Name: " + getName() + " Age: " + getAge() + " Address: " + getAddress() + " Salary: " + getSalary() + "KM\n----------------------------------------------------------------------------------------------\n"; } } }
Key Notes:
- The
initialize()method runs automatically when the FXML loads, making it ideal for setup tasks like listeners and initial data loading. - We added a
loadAllEmployees()helper method to keep code clean and reusable across parts of your app. - In the
update()method, we clearupdateListbefore adding new items to prevent duplicate entries. - Integer values (age, salary) are converted to strings since TextFields only accept String input.
内容的提问来源于stack exchange,提问作者LjubisaK

