JavaFX ListView使用CSS圆角

问题描述

我希望ListView上有圆角。我当前拥有的CSS会四角,直到我向ListView添加新的字符串,然后四角不再圆了。我正在使用ObservableList来存储我的字符串,并将ListView设置为ObservableList。

我还检查了JavaFX CSS参考,但找不到对我的问题有用的任何东西。

No text
After text is added

我当前的CSS

.list-view {
    -fx-background-radius: 20px;
}

解决方法

在您的示例中,列表单元格的默认样式与列表视图的圆形背景重叠。您可以在列表视图中添加一些填充,以便没有任何重叠。列表视图的项目也可以具有圆形边框。

FXML:

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

<?import java.lang.String?>
<?import javafx.collections.FXCollections?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.HBox?>


<HBox spacing="10.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <ListView fx:id="listView1" style="-fx-background-radius: 20;">
         <items>
            <FXCollections fx:factory="observableArrayList">
               <String fx:value="Item 1" />
               <String fx:value="Item 2" />
               <String fx:value="Item 3" />
            </FXCollections>
         </items>
         <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
         </padding>
      </ListView>
      <ListView fx:id="listView" stylesheets="@styling.css">
         <items>
            <FXCollections fx:factory="observableArrayList">
               <String fx:value="Item 1" />
               <String fx:value="Item 2" />
               <String fx:value="Item 3" />
            </FXCollections>
         </items>
         <padding>
            <Insets bottom="7.0" left="7.0" right="7.0" top="7.0" />
         </padding>
      </ListView>
   </children>
   <padding>
      <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
   </padding>
</HBox>

styling.css (用于第二个列表视图):

.list-view {
    -fx-background-radius: 20;
}

.list-cell,.list-cell::focused {
    -fx-border-radius: 20;
}

预览:

enter image description here