JavaFx:How to create a List View in Java Fx?
For generating List View you should have a structure as provided below in JavaFx project.
We have created this List View to display the selected value in console. You can modify code according to your requirement.
Main.java
package application_listview;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root=FXMLLoader.load(getClass().getResource("/application_listview/Main.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainController.java
package application_listview;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
public class MainController implements Initializable {
@FXML
public ListView<String> listview;
ObservableList<String> list=FXCollections.observableArrayList("one","two","three","four");
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
listview.setItems(list);
listview.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
public void buttonAction(ActionEvent event){
ObservableList<String> names;
names=listview.getSelectionModel().getSelectedItems();
for(String name :names){
System.out.println(name);
}
}
}
Main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="300.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application_listview.MainController">
<children>
<ListView fx:id="listview" layoutX="50.0" layoutY="72.0" prefHeight="200.0" prefWidth="200.0" />
<Button layoutX="124.0" layoutY="25.0" mnemonicParsing="false" onAction="#buttonAction" text="Button" />
</children>
</AnchorPane>
No comments:
Post a Comment