在JavaFX

时间:2016-11-27 15:42:26

标签: css listview javafx width

这是使用javaFX的聊天应用程序的界面。聊天窗口是一个ListView组件,我正在使用CSS来稍微抛光它。这是CSS和截图: enter image description here

.list-cell {
  display: inline-block;
  -fx-min-width: 50px;
  -fx-background-color: lightyellow;
  -fx-background-radius: 30px;
  -fx-border-radius: 20px;
  -fx-border-width: 2px;
  -fx-border-style: solid;
  -fx-border-color: #666666;
}
.list-cell:empty {
  -fx-background-color: transparent;
  -fx-border-width: 0px;
}

问题是我想根据文本的长度更改每个listCell的宽度。我尝试在CSS文件中设置minWidth prefWidth(例如50px)或使用listView.setCellFactory但没有任何反应。长度根本不变。我想知道我可以改变listView中每个单元格的长度吗(或者为了做到这一点,我必须使用像HBox / VBox / seperator这样的东西......)

1 个答案:

答案 0 :(得分:1)

使用将图形设置为Label的单元工厂,并为标签设置样式。 E.g:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

public class FormattedListCell extends Application {

    @Override
    public void start(Stage primaryStage) {
        ListView<String> listView = new ListView<>();
        listView.getItems().addAll("One", "Two", "Three", "Four");

        listView.setCellFactory(lv -> new ListCell<String>() {
            private final Label label = new Label();
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    label.setText(item);
                    setGraphic(label);
                }
            }
        });

        Scene scene = new Scene(listView, 400, 400);
        scene.getStylesheets().add("formatted-list-cell.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

并修改样式表:

.list-cell .label {
  display: inline-block;
  -fx-min-width: 50px;
  -fx-background-color: lightyellow;
  -fx-background-radius: 30px;
  -fx-border-radius: 20px;
  -fx-border-width: 2px;
  -fx-border-style: solid;
  -fx-border-color: #666666;
}
.list-cell:empty .label {
  -fx-background-color: transparent;
  -fx-border-width: 0px;
}

您可能需要实际设置列表单元格的样式(以及其中的标签)以获得您想要的确切样式,但这应该可以帮助您入门。

enter image description here

这是一个更完整的CSS文件,使用-fx-background,以便文本颜色自动调整,管理选择颜色,并为列表单元格本身添加一些样式:

.list-cell {
    -fx-background-color: transparent ;
    -fx-padding: 0 ;
}

.list-cell .label {
  display: inline-block;
  -fx-background: lightyellow;
  -fx-background-color: -fx-background ;
  -fx-background-radius: 30px;
  -fx-border-radius: 20px;
  -fx-border-width: 2px;
  -fx-border-style: solid;
  -fx-border-color: #666666;
  -fx-padding: 12px ;
}
.list-cell:empty .label {
  -fx-background-color: transparent;
  -fx-border-width: 0px;
}
.list-cell:selected .label {
    -fx-background: -fx-selection-bar ;
}

enter image description here