2016-03-25 30 views
1

私はplayerNameとScoreを持つクラスを持っています。私はこのクラスのObservableListを自分のControllerクラスに作成しました。プレイヤーとスコアがこの配列に追加されます。しかし、問題はどのように私はスコアに応じてそれを並べ替えるのですか?ObservableList <Class>を値の昇順と降順で並べ替える - JAVAFX

ObservableList<PlayerScore> playerScores = FXCollections.observableArrayList(); 

これは、これまでにどのように見えるかです:

//stateACS is a toggle button 
if (stateASC.isSelected()) { 
    //Sort in asc order by player score 
    FXCollections.sort(playerScores); 
}else{ 
    //sort in desc order by player score 

} 
+1

なぜタイプ 'クラス'を使用するのか分かりません。これを説明できますか? –

+0

これは単なる例であり、クラスの実名はPlayerScoresです。私は今質問を更新しました。 –

答えて

2

あなたが与えられた基準によって任意のリストを並べ替えるだけで同じ方法:Comparator、例えばを使用することによりClassは、クラス名のお粗末な選択である理由の名前の衝突のjava.lang.Class

0

あなたはコンパレータを実装して、コンパレータのインスタンスでソートメソッドを使用して配列をソートすることができます。ところで

// assuming there is a instance method Class.getScore that returns int 
// (other implementations for comparator could be used too, of course) 
Comparator<Class> comparator = Comparator.comparingInt(Class::getScore); 
if (!stateASC.isSelected()) { 
    comparator = comparator.reversed(); 
} 
FXCollections.sort(playerScores, comparator); 

https://docs.oracle.com/javase/8/javafx/api/javafx/collections/FXCollections.html#sort-javafx.collections.ObservableList-java.util.Comparator-

関連する問題