Skip to content

Instantly share code, notes, and snippets.

@alvareztech
Created May 3, 2017 17:51
Show Gist options
  • Save alvareztech/b5ea06478778de7225bdb4bd2bd8a71c to your computer and use it in GitHub Desktop.
Save alvareztech/b5ea06478778de7225bdb4bd2bd8a71c to your computer and use it in GitHub Desktop.
JavaFX: Eliminación item de un ListView
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
ListView<String> listView = new ListView<>();
ObservableList<String> items = FXCollections.observableArrayList("Uno", "Dos", "Tres", "Cuatro");
listView.setItems(items);
Button eliminarButton = new Button("Eliminar");
eliminarButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
int posicionAEliminar = listView.getSelectionModel().getSelectedIndex();
System.out.println(">" + posicionAEliminar);
if (posicionAEliminar >= 0) {
items.remove(posicionAEliminar);
} else {
System.out.println("No se puede eliminar, nada seleccionado.");
}
}
});
VBox vBox = new VBox();
vBox.getChildren().add(listView);
vBox.getChildren().add(eliminarButton);
vBox.setSpacing(20);
vBox.setPadding(new Insets(20, 20, 20, 20));
Scene scene = new Scene(vBox, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment