我有TableColumn<User, String> colPassword
当前仅显示为每个条目(行)屏蔽的现有密码(字符串)。
我需要您的帮助,以便每个TableCell
仅显示 屏蔽的 密码(如果相应行的用户: user.isManager = = true ,否则密码应 取消屏蔽 。
我将只提供关键部分以便于理解。
public class User implements Serializable {
private Long id;
private boolean deleted = false;
private final BooleanProperty manager = new SimpleBooleanProperty();
private final StringProperty password = new SimpleStringProperty("");
public User() {
}
public boolean isManager() {
return manager.get();
}
public void setManager(boolean value) {
manager.set(value);
}
public BooleanProperty managerProperty() {
return manager;
}
GUI的UserController
public class UsersController {
@FXML
private TableView<User> tblUsers;
@FXML
private TableColumn<User, String> colPassword;
private void initTableColumns() {
colPassword.setCellValueFactory(cellData
-> cellData.getValue().passwordProperty()
);
colPassword.setCellFactory((TableColumn<User, String> param) -> {
return new PasswordFieldCell();
});
}
这是自定义TabelCell
public class PasswordFieldCell extends TableCell<User, String> {
private final Label lbl;
public PasswordFieldCell() {
lbl = new Label();
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setGraphic(null);
}
private String generatePasswordString(int len) {
String dots = "";
for (int i = 0; i < len; i++) {
dots += "*";
}
return dots;
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
lbl.setText(generatePasswordString(item.length()));
setGraphic(lbl);
} else {
setGraphic(null);
}
}
}
在VGR的帮助下,我能够在PasswordFieldCell中提出这个解决方案。
public class PasswordFieldCell extends TableCell<User, String> {
private final Label lbl;
public PasswordFieldCell() {
lbl = new Label();
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setGraphic(null);
}
private String generatePasswordString(int len) {
String dots = "";
for (int i = 0; i < len; i++) {
dots += "*";
}
return dots;
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
int row = getIndex();
User user = getTableView().getItems().get(row);
if (user.isManager()) { // mask password
lbl.setText(generatePasswordString(item.length()));
} else { // unmask password
lbl.setText(item);
}
setGraphic(lbl);
} else {
setGraphic(null);
}
}
}
答案 0 :(得分:1)
您的PasswordFieldCell类从TableCell继承了许多有用的方法。
特别是,您继承了getTableView()方法和getIndex()方法,该方法返回当前单元格的行。您只需要在updateItem
方法中查找单元格的行值:
int row = getIndex();
User user = getTableView().getItems().get(row);