Skip to content

Instantly share code, notes, and snippets.

@Zookey
Created May 20, 2012 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zookey/2759663 to your computer and use it in GitHub Desktop.
Save Zookey/2759663 to your computer and use it in GitHub Desktop.
JavaFX 2 ListView Handle Action
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* @author zoranpavlovic.blogspot.com
*/
public class ListViewMain extends Application {
/**
* @param args the command line arguments
*/
StackPane sp = new StackPane();
ListView<String> list = new ListView<>();
ObservableList<String> data =FXCollections.observableArrayList (
"List index 0",
"List index 1",
"List index 2",
"List index 3",
"List index 4",
"List index 5");
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX 2.0 ListView");
//Adding data to ListView
list.setItems(data);
//Actions on clicked list item
initActions();
//Adding BorderPane to the scene
sp.getChildren().add(list);
Scene scene = new Scene(sp,300,200);
primaryStage.setScene(scene);
primaryStage.show();
}
public void initActions(){
//Detecting mouse clicked
list.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent arg0) {
//Check wich list index is selected then set txtContent value for that index
if(list.getSelectionModel().getSelectedIndex() == 0){
System.out.println("Selected index: 0");
}
else if(list.getSelectionModel().getSelectedIndex() == 1){
System.out.println("Selected index: 1");
}
else if(list.getSelectionModel().getSelectedIndex() == 2){
System.out.println("Selected index: 2");
}
else if(list.getSelectionModel().getSelectedIndex() == 3){
System.out.println("Selected index: 3");
}
else if(list.getSelectionModel().getSelectedIndex() == 4){
System.out.println("Selected index: 4");
}
else if(list.getSelectionModel().getSelectedIndex() == 5){
System.out.println("Selected index: 5");
}
}
});
}
}
@sayeedajmal
Copy link

Thanks! Dude!

@sayeedajmal
Copy link

great! i appreciate !!!!!

@Jesperilmari
Copy link

Nice!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment