정렬 된 관찰 가능 목록을 사용하는 경우에도 콤보 상자가 정렬되지 않는 이유는 무엇입니까?

iXô

javafx의 콤보 상자에 정렬 된 항목 목록을 표시하려고합니다.

내 컨트롤러에서 내 항목 목록은 다음과 같이 선언됩니다.

private final ObservableList<Profile> profiles = FXCollections.observableArrayList();
private final SortedList<Profile> sortedProfiles = new SortedList<>(profiles);

내 콤보 상자는 다음과 같이 초기화됩니다.

profiles.setItems(controller.getSortedProfiles());

그런 다음 컨트롤러에 항목을 추가 할 수있는 방법이 있습니다.

profiles.add(new Profile(profileName));

콤보 상자가 업데이트되지만 정렬되지는 않습니다. 왜 ? 정렬 목록 래퍼를 사용하면 콤보 상자가 정렬 된 상태로 유지 될 것이라고 생각했습니다.

샘플 코드 :

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.util.Random;

public class Demo extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    public void start(Stage primaryStage) throws Exception {
        final ObservableList<Item> items = FXCollections.observableArrayList();

        items.add(new Item(1));
        items.add(new Item(100));
        items.add(new Item(10));

        final SortedList<Item> itemSortedList = new SortedList<>(items);

        final BorderPane view = new BorderPane();

        final ComboBox<Item> profiles = new ComboBox<>();
        final Button add = new Button("add random");
        add.setOnAction(event -> items.add(new Item(new Random().nextInt(5000))));

        profiles.setItems(itemSortedList);

        view.setTop(profiles);
        view.setBottom(add);

        final Scene scene = new Scene(view, 400, 400);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private static final class Item implements Comparable<Item> {
        private Integer name;

        public Item(final int name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Int : " + name;
        }

        @Override
        public int compareTo(final Item o) {
            return name.compareTo(o.name);
        }
    }
}
파비안

comparator정렬 된 목록 속성을 설정하지 않았습니다 . javadoc 에는 comparator속성 에 대한 다음 문이 포함되어 있습니다.

이 SortedList의 순서를 나타내는 비교기입니다. 정렬되지 않은 SortedList의 경우 Null입니다.

즉, 비교자를 지정하지 않고 목록은 단순히 원래 목록의 순서를 유지합니다. 비교기를 지정하여 문제를 해결하십시오.

final SortedList<Item> itemSortedList = new SortedList<>(items, Comparator.naturalOrder());

또는 적절한 getter를 추가하면 Comparator주어진 속성별로 정렬을 쉽게 만들 수 있습니다 (이 속성이 비교할 수있는 경우).

final SortedList<Item> itemSortedList = new SortedList<>(items, Comparator.comparing(Item::getName));

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관