2016-05-20 3 views
1

javafx.scene.control.ChoiceBoxにテキストを水平に配置する方法はありますか? ChoiceBoxにテキストを中央に配置することを検討しています。また、値を選択するときに開くドロップダウンも表示されます。JavaFXの選択ボックス内でテキストを水平方向に中央に揃える方法

+3

代わりに、ComboBoxを代わりに使用し、そのcellFactoryおよびbuttonCellプロパティを設定します。 – VGR

答えて

1

@ VGRの推奨に従って、実装をjavafx.scene.control.ComboBoxに変更しました。その後、私はCenteredListCellというクラスを作成しました:

import javafx.geometry.Pos; 
import javafx.scene.control.ListCell; 

public class CenteredListCell<T> extends ListCell<T> { 

    /** Default constructor */ 
    public CenteredListCell() { 
     setMaxWidth(Double.POSITIVE_INFINITY); 
     setAlignment(Pos.BASELINE_CENTER); 
    } 

    @Override 
    public void updateItem(final T item, final boolean empty) { 
     super.updateItem(item, empty); 
     setText(empty || item == null ? null : item.toString()); 
    } 

} 

次へ]を、私は(runWhenSkinnedにつながるインスピレーションを得るため@kleopatraのおかげ)以下のユーティリティメソッドを作成しました:

private static void runWhenSkinned(final Control control, final Runnable operation) { 
    final ReadOnlyObjectProperty<?> skinProperty = control.skinProperty(); 
    if (skinProperty.get() == null) { 
     // Run after the control has been skinned 
     skinProperty.addListener(observable -> Platform.runLater(operation)); 
    } else { 
     // Run now, since the control is already skinned 
     operation.run(); 
    } 
} 

public static <T> void center(final ComboBox<T> comboBox) { 
    runWhenSkinned(comboBox,() -> { 
     // Get the width of the combo box arrow button 
     final Region arrow = (Region)comboBox.lookup(".arrow-button"); 
     final double arrowWidth = arrow.getWidth(); 

     // Create a centered button cell 
     final ListCell<T> buttonCell = new CenteredListCell<T>(); 
     comboBox.setButtonCell(buttonCell); 

     // Create an insets object with uneven horizontal padding 
     final Insets oldPadding = buttonCell.getPadding(); 
     final Insets newPadding = new Insets(oldPadding.getTop(), 
       arrowWidth, oldPadding.getBottom(), 0); 

     // Replace the default cell factory 
     comboBox.setCellFactory(listView -> new CenteredListCell<T>() { 
      { setPadding(newPadding); } 
     }); 
    }); 
} 

最終結果ボタンセルと項目のリストビューの両方に中央揃えのテキストを持つComboBoxです。

+1

コンボのスキンプロパティにリスナーを登録し、新しいスキンが通知されたらユーティリティメソッドを呼び出すことができます – kleopatra

関連する問題