JavaFX: Eliminación item de un ListView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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