javafx中设置ListView样式

javafx中ListView默认样式是这样:

怎样让它变成这样:(奇数行为白色,偶数行为绿色,选中为黄色,空白为白色)

fx中支持css,因此实现很简单,只需要加入以下样式:

.list-cell:even {
    -fx-background-color: white;
}
.list-cell:odd {
    -fx-background-color: green;
}
.list-cell:selected {
    -fx-background-color: yellow;
}
.list-cell:empty {
    -fx-background-color: white;
}

ListViewTest源码如下:

public class ListViewTest extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void start(Stage stage) throws Exception {
        final ListView lv = new ListView();
        lv.setPrefHeight(200);
        lv.setPrefWidth(200);
        lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        for (int i = 0; i < 3; i++)
            lv.getItems().add(i);

        Button addButton = new Button("Add 10 on position 2");
        addButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                lv.getItems().add(2, 10);
            }
        });

        Pane pane = new Pane();
        pane.getChildren().add(lv);

        VBox vb = new VBox();
        vb.getChildren().addAll(pane, addButton);

        Scene scene = new Scene(vb);
        scene.getStylesheets().add(
                this.getClass().getResource("listview.css").toExternalForm());
        stage.setScene(scene);
        stage.show();
    }
}

更多源码下载...

posted on 2012-11-30 16:09  韩细  阅读(4528)  评论(0编辑  收藏  举报