JavaFX ListView使用和样式设置

时间:2023-01-19 17:05:02

1、新建一个fxml界面文件,里面就放置一个ListView

对应的Controller为ListViewTestController,css配置文件为ListViewTest.css

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.VBox?>
<VBox alignment="CENTER" stylesheets="@../css/ListViewTest.css" xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.nii.desktop.controller.ListViewTestController">
<children>
<ListView fx:id="studentListView" maxWidth="500.0" minWidth="500.0" prefHeight="300.0" prefWidth="490.0" />
</children>
</VBox>

2、ListViewTestController代码

将界面的数据映射为dataList,更改界面数据,只需更改dataList值就可以,代码如下
package com.nii.desktop.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;

import java.net.URL;
import java.util.ResourceBundle;

/**
* Created by wzj on 2017/11/1.
*/
public class ListViewTestController implements Initializable
{
/**
* listview
*/
@FXML
private ListView studentListView;

/**
* listciew数据
*/
private ObservableList<String> dataList = FXCollections.observableArrayList();

/**
* Called to initialize a controller after its root element has been
* completely processed.
*
* @param location The location used to resolve relative paths for the root object, or
* <tt>null</tt> if the location is not known.
* @param resources The resources used to localize the root object, or <tt>null</tt> if
*/
@Override
public void initialize(URL location, ResourceBundle resources)
{
studentListView.setItems(dataList);

dataList.add("张三");
dataList.add("李四");
dataList.add("王五");
dataList.add("李华");

dataList.add("张三");
dataList.add("李四");
dataList.add("王五");
dataList.add("李华");

dataList.add("张三");
dataList.add("李四");
dataList.add("王五");
dataList.add("李华");

}
}

3、CSS样式设置

主要是设置界面字体的颜色、字体和行高
.list-cell{
-fx-text-fill: #292e34;
-fx-font-family: Arial;
-fx-pref-height: 30px;
}

最终的效果如下:
JavaFX ListView使用和样式设置