public class TableViewSample extends Application {
// Stores the state of the TableView and opens the second window
TablePopUp popUp = new TablePopUp();
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Scene scene = new Scene(new BorderPane());
stage.setTitle("Table View Sample");
stage.setWidth(450);
stage.setHeight(550);
BorderPane root = (BorderPane) scene.getRoot();
Button button = new Button("Open window");
button.setOnAction((e) -> popUp.showTable());
root.setCenter(button);
stage.setScene(scene);
stage.show();
}
class TablePopUp {
// Stores the Person object which were added and applied but not stored
// in DB
ObservableList<Person> bufferAdd = FXCollections.observableArrayList();
// Simulate the items coming from the DV
private ObservableList<Person> dataFromDB = FXCollections.observableArrayList(
new Person("Jacob", "Smith", "[email protected]"),
new Person("Isabella", "Johnson", "[email protected]"),
new Person("Ethan", "Williams", "[email protected]"),
new Person("Emma", "Jones", "[email protected]"),
new Person("Michael", "Brown", "[email protected]"));
void showTable() {
// Temporary buffer for the added Persion objects
ObservableList<Person> tempBuffer = FXCollections.observableArrayList();
// Temporary buffer to store persons to be deleted on apply
ObservableList<Person> bufferRemoveFromBuffer = FXCollections.observableArrayList();
// Data what the TableView displays
ObservableList<Person> tableData = FXCollections.observableArrayList();
// Stores the person objects that will be removed from the DB if Save is pressed
ObservableList<Person> bufferRemoveFromDB = FXCollections.observableArrayList();
// The Table displays elements from the DB + the applied buffer
tableData.addAll(dataFromDB);
tableData.addAll(bufferAdd);
// Create the table
TableView<Person> table = new TableView<Person>();
table.setItems(tableData);
Scene scene = new Scene(new BorderPane());
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
TableColumn emailCol = new TableColumn("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
TextField addFirstName = new TextField();
addFirstName.setPromptText("First Name");
addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
TextField addLastName = new TextField();
addLastName.setMaxWidth(lastNameCol.getPrefWidth());
addLastName.setPromptText("Last Name");
TextField addEmail = new TextField();
addEmail.setMaxWidth(emailCol.getPrefWidth());
addEmail.setPromptText("Email");
// Button to add a new Person
Button addButton = new Button("Add");
addButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Person newPerson = new Person(addFirstName.getText(), addLastName.getText(), addEmail.getText());
// Add a new element to the temporary buffer and add it to
// the table data also
tempBuffer.add(newPerson);
tableData.add(newPerson);
addFirstName.clear();
addLastName.clear();
addEmail.clear();
}
});
// Button to remove a Person
Button removeButton = new Button("Remove");
removeButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Person selectedItem = table.getSelectionModel().getSelectedItem();
if(selectedItem != null) {
// Remove the item from the list of the displayed persons
tableData.remove(selectedItem);
// Check the buffers: if one of the buffer contains the selected item, remove it from the buffer
if(tempBuffer.contains(selectedItem))
tempBuffer.remove(selectedItem);
else if(bufferAdd.contains(selectedItem))
bufferRemoveFromBuffer.add(selectedItem);
else {
// The item is not in the buffers -> remove the item from the DB
bufferRemoveFromDB.add(selectedItem);
}
}
}
});
HBox hb = new HBox();
hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton, removeButton);
hb.setSpacing(3);
VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
BorderPane root = (BorderPane) scene.getRoot();
root.setCenter(vbox);
Stage stage = new Stage();
HBox applySave = new HBox();
// On Save:
// Remove all elements from the buffer that were selected to be deleted
// Remove all elements from the BD that were selected to be deleted
// Add all the elements from the persistent buffer to the DB
// Add all the elements from the temporary buffer to the DB
// Clear both buffers
Button saveButton = new Button("Save to DB");
saveButton.setOnAction((e) -> {
bufferAdd.removeAll(bufferRemoveFromBuffer);
dataFromDB.removeAll(bufferRemoveFromDB);
dataFromDB.addAll(bufferAdd);
dataFromDB.addAll(tempBuffer);
bufferAdd.clear();
stage.close();
});
// On Apply:
// Add elements from the temporary buffer to the persistent buffer
// Remove elements from the buffer
Button applyButton = new Button("Apply");
applyButton.setOnAction((e) -> {
bufferAdd.addAll(tempBuffer);
bufferAdd.removeAll(bufferRemoveFromBuffer);
stage.close();
});
applySave.getChildren().addAll(saveButton, applyButton);
root.setBottom(applySave);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setScene(scene);
stage.show();
}
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private Person(String fName, String lName, String email) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
}
}
클래스 TablePopUp
실제로 두 개의 버퍼를 갖는다. "적용"버튼을 누르면 임시 버퍼가 영구 버퍼에 저장됩니다. "저장"버튼을 누르면 두 버퍼가 모두 DB에 저장되고 버퍼가 지워집니다.
이 예에서는 제거도 버퍼링됩니다. 제거시 데이터베이스에서 제거할지 여부를 결정하는 Person
오브젝트가 발견됩니다. 데이터베이스에서 오는 경우 버퍼에 저장되며 저장 버튼을 누르면 데이터베이스에서 제거됩니다. 추가 된 사람이지만 데이터베이스에 아직 배치되지 않은 사람에게는 동일한 워크 플로우가 유효합니다. 제거시 적용 단추를 누르면 제거됩니다.
그래서 창을 열 때 DB에서 오는 항목이 테이블의 초기 상태입니다. 그런 다음 저장 또는 적용을 누를 수 있습니다. 저장은 항목을 DB에 저장하고, 적용은 항목을 DB에 저장하고 창을 닫습니다. 두 버튼의 차이점은 Apply가 창을 닫는 것입니다. 나는 그것을 잘 이해하고 있는가? 다음 오픈시 항목이 DB에서 왔기 때문에 (초기 상태이므로) 항목이 이전 창에서 DB에 저장되었으므로이 질문을 이해할 수 없습니다. 아니면 오타가 있습니다 : "세 번째 레코드는 DB에 저장되지 않습니다 ..."? – DVarga
저장 버튼 만 누르면 테이블 데이터가 DB에 저장됩니다. APPLY 버튼은 테이블 데이터를 DB에 저장하지 않습니다. 적용 버튼을 사용하면 테이블의 현재 상태를 저장하려고합니다. 예 : 나는 처음으로 tableview를 열 때. 그리고 DB에서 오는 두 개의 레코드가 있다면. 이제 테이블에 행/레코드를 하나 더 추가하고 APPLY 버튼을 클릭하면 DB에 아무 것도 삽입되지 않지만 테이블의 현재 상태 (세 행 있음)가 유지되어야하며 다음에 테이블을 열 때 세 행이 유지되어야합니다. 표시된 (처음 두 DB에서) 및 세 번째 하나는 내가 추가 한 –
그래서, 세 번째는 메모리에 저장됩니다?'TableView'에 대해이 데이터 소스를 가져 오기 위해 속성을 생성해야하는 것처럼 들리지만, 행이 데이터베이스에 존재하지 않는지 확인하십시오. 그렇다면 행을 애플리케이션의 객체로 저장하십시오. 지금까지 뭐 해봤 어? 'TableView'가 어떻게 쓰이고 어떻게 데이터로 채우는 지에 대한 샘플 코드가 있습니까? – Draken