Social

lunes, 10 de junio de 2013

JavaFX: Agregar y eliminar filas de una tabla (TableView) dinamicamente

Es recomendable ver antes: JavaFX: Agregar Tabla

Los elementos del tipo TableView en JavaFX usan una lista observable para permitir administrar su contenido. Además JavaFX permite la creación de celdas personalizadas, podemos agregar muchos elementos visuales. En este caso usamos un botón (Button) para permitir para eliminar un elemento de la tabla.


Para realizar lo anterior se puede utilizar el siguiente código:

import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class AddDeleteTable extends Application {
private TableView<Person> table;
private TextField txtFirst;
private TextField txtSecond;
private TextField txtPhone;
private Button addButton;
private ObservableList<Person> data;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Group group = new Group();
Scene scene = new Scene(group);
stage.setTitle("Table View Sample");
stage.setWidth(400);
stage.setHeight(500);
table = new TableView<Person>();
txtFirst = new TextField();
txtFirst.setMaxWidth(100);
txtSecond = new TextField();
txtSecond.setMaxWidth(100);
txtPhone = new TextField();
txtPhone.setMaxWidth(100);
addButton = new Button("Agregar");
data = FXCollections.observableArrayList(
new Person("Paco", "Perez", "12345678"),
new Person("Isabella", "Garcia","12345678"),
new Person("Juan", "Juanes", "12345678"),
new Person("German", "Jones","12345678"),
new Person("Erick", "Mancha", "12345678"));
table.setEditable(true);
table.setMinWidth(390);
TableColumn firstNameCol = new TableColumn("Primer Nombre");
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
firstNameCol.setMinWidth(100);
TableColumn lastNameCol = new TableColumn("Segundo Nombre");
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
lastNameCol.setMinWidth(100);
TableColumn phoneCol = new TableColumn("Teléfono");
phoneCol.setCellValueFactory(new PropertyValueFactory<Person, String>("phone"));
phoneCol.setMinWidth(100);
//Se agrega la celda modificada con el botón a la tabla
TableColumn buttonCol = new TableColumn<>("Borrar");
buttonCol.setSortable(false);
buttonCol.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Person, Boolean>,
ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Person, Boolean> p) {
return new SimpleBooleanProperty(p.getValue() != null);
}
});
//Indicamos que muestre el ButtonCell creado mas abajo.
buttonCol.setCellFactory(
new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() {
@Override
public TableCell<Person, Boolean> call(TableColumn<Person, Boolean> p) {
return new ButtonCell(table);
}
});
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, phoneCol, buttonCol);
HBox texts = new HBox();
texts.setMaxWidth(380);
texts.getChildren().add(txtFirst);
texts.getChildren().add(txtSecond);
texts.getChildren().add(txtPhone);
texts.getChildren().add(addButton);
addButton.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent evt) {
data.add(new Person(txtFirst.getText(),txtSecond.getText(),txtPhone.getText()));
}
});
VBox capa = new VBox();
capa.getChildren().add(table);
capa.getChildren().add(texts);
group.getChildren().add(capa);
stage.setScene(scene);
stage.show();
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty phone;
private Person(String first, String last, String phon) {
this.firstName = new SimpleStringProperty(first);
this.lastName = new SimpleStringProperty(last);
this.phone = new SimpleStringProperty(phon);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String first) {
firstName.set(first);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String last) {
lastName.set(last);
}
public String getPhone() {
return phone.get();
}
public void setEmail(String phone) {
this.phone.set(phone);
}
}
private class ButtonCell extends TableCell<Person, Boolean> {
//boton a mostrar
final Button cellButton = new Button("Borrar");
ButtonCell(final TableView tblView){
cellButton.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent t) {
int selectdIndex = getTableRow().getIndex();
//borramos el objeto obtenido de la fila
data.remove(selectdIndex);
}
});
}
//Muestra un boton si la fila no es nula
@Override
protected void updateItem(Boolean t, boolean empty) {
super.updateItem(t, empty);
if(!empty){
setGraphic(cellButton);
}
}
}
}

Básicamente los elementos del código son  la inicialización de la ventana y tabla, agregar las columnas (incluyendo la que muestra el botón a la tabla), el área para agregar una nueva fila (línea 100) que básicamente solo agrega más objetos a una lista observable, la clase ButtonCell que nos permite agregar el botón dentro un celda (donde se agrega la funcionalidad) y el pojo persona para manejar la información.

No hay comentarios :

Publicar un comentario