Формат даты в JavaFX.TableViewJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Формат даты в JavaFX.TableView

Сообщение Anonymous »

Я столкнулся с проблемой.

У меня есть класс POJO:

public class PatientEntity {

private int id;
private Date dateDoc;
private String secondname;
private String firstname;
private String thirdname;

@Id
@Column(name = "ID")
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Basic
@Column(name = "Date_doc")
public Date getDateDoc() {
return dateDoc;
}

public void setDateDoc(Date dateDoc) {
this.dateDoc = dateDoc;
}


Я использую JavaFX.TableView таким образом, чтобы заполнить:

columnID.setCellValueFactory(new PropertyValueFactory
("id"));
columnDate.setCellValueFactory(new PropertyValueFactory("dateDoc"));
columnSecondname.setCellValueFactory(new PropertyValueFactory("secondname"));
columnFirstname.setCellValueFactory(new PropertyValueFactory("firstname"));
columnThirdname.setCellValueFactory(new PropertyValueFactory("thirdname"));

tableView.setItems(FXCollections.observableList(patients));


Результат:
результат запуска

Работает нормально, но мне нужен другой формат даты, например дд.мм.гггг в TableView. Итак, как я могу это сделать? Как видите, TableView содержит объекты, а не простые строки.

Изменено №1

private synchronized void updateTableView(List
patients){

columnID.setCellValueFactory(new PropertyValueFactory("id"));
columnDate.setCellFactory(column -> {
TableCell cell = new TableCell() {
private SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");

@Override
protected void updateItem(Date item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
}
else {
this.setText(format.format(item));

}
}
};

return cell;
});

columnSecondname.setCellValueFactory(new PropertyValueFactory("secondname"));
columnFirstname.setCellValueFactory(new PropertyValueFactory("firstname"));
columnThirdname.setCellValueFactory(new PropertyValueFactory("thirdname"));
tableView.setItems(FXCollections.observableList(patients));
}


Такой результат

Отредактировано №2

private void updateTableView(){
Thread threadConnectingToDB = new Thread(() -> {
try {
List
patients;
PatientDAO patientDAO = FactoryDAO.getInstance().getPatientDAO();
if(patientDAO.getAllPatients() instanceof List){
patients = (List) patientDAO.getAllPatients();
} else {
patients = new ArrayList(patientDAO.getAllPatients());
}
columnID.setCellValueFactory(new PropertyValueFactory("id"));
columnDate.setCellValueFactory(new PropertyValueFactory("doc_date"));
columnDate.setCellFactory(column -> {
TableCell cell = new TableCell() {
private SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");

@Override
protected void updateItem(Date item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
}
else {
if(item != null)
this.setText(format.format(item));
}
}
};

return cell;
});

columnSecondname.setCellValueFactory(new PropertyValueFactory("secondname"));
columnFirstname.setCellValueFactory(new PropertyValueFactory("firstname"));
columnThirdname.setCellValueFactory(new PropertyValueFactory("thirdname"));
tableView.setItems(FXCollections.observableList(patients));

} catch (SQLException e) {
try {
ErrorStage.display("Произошла ошибка при подключении к базе данных");
} catch (Exception e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
});
threadConnectingToDB.start();
threadConnectingToDB.interrupt();
}


Решение

Спасибо @mr mcwolf, решение есть!

Нам нужны два метода:
Первый метод — это метод конфигурации, который мы вызываем один раз во время инициализации:

private void configureTableView(){
columnID.setCellValueFactory(new PropertyValueFactory
("id"));
columnDate.setCellFactory(column -> {
TableCell cell = new TableCell() {
private SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");

@Override
protected void updateItem(Date item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
}
else {
this.setText(format.format(item));

}
}
};

return cell;
});
columnDate.setCellValueFactory(new PropertyValueFactory("dateDoc"));
columnSecondname.setCellValueFactory(new PropertyValueFactory("secondname"));
columnFirstname.setCellValueFactory(new PropertyValueFactory("firstname"));
columnThirdname.setCellValueFactory(new PropertyValueFactory("thirdname"));

}


И нам нужен метод для заполнения tableView:

private synchronized void fillTableView(List patientsList){

Thread threadConnectingToDB = new Thread(() -> {
try {
List patients = patientsList;
if(patients == null) {
PatientDAO patientDAO = FactoryDAO.getInstance().getPatientDAO();
if (patientDAO.getAllPatients() instanceof List) {
patients = (List) patientDAO.getAllPatients();
} else {
patients = new ArrayList(patientDAO.getAllPatients());
}
}
tableView.setItems(FXCollections.observableList(patients));
} catch (SQLException e) {
try {
ErrorStage.display("Error Connection");
} catch (Exception e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
});
threadConnectingToDB.start();
threadConnectingToDB.interrupt();
}


Подробнее здесь: https://stackoverflow.com/questions/474 ... -tableview
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»