2014-03-05 56 views
4

组合框的下拉列表展开为其中输入的最大元素的大小,但我希望它的大小固定。如何在java中设置组合框的下拉宽度fx

--------------------- 
| Small Combobox | V | 
-------------------------------------------- 
| "Long item 1"        | 
-------------------------------------------- 
| "Long item 2"        | 
-------------------------------------------- 
| "Long item 3"        | 
-------------------------------------------- 
+0

尝试过'prefWidth()'? – ItachiUchiha

+0

是的,我已经尝试prefWidth()设置的组合框大小不是其下拉 – vinay

+0

你有一个SSCCE - http://sscce.org为您的支持? – ItachiUchiha

回答

9

使用CSS

/** file: combo-size.css */ 

/** Size the combo-box button. */ 
.combo-box { 
    -fx-pref-width: 100; 
} 

/** Size the combo-box drop down list. */ 
.combo-box-popup > .list-view { 
    -fx-pref-width: 100; 
} 

注:我只对Java的8测试此示例,我相信-fx-*-width-fx-*-height CSS属性可以为JavaFX 8是新的。

示例用法

在此示例中,无论是组合框按钮和下拉列表已经被尺寸设置成相同的优选宽度(100个像素)。

enter image description here

import javafx.application.Application; 
import javafx.geometry.Insets; 
import javafx.scene.Scene; 
import javafx.scene.control.ComboBox; 
import javafx.scene.layout.StackPane; 
import javafx.scene.text.Font; 
import javafx.stage.Stage; 

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

    @Override public void start(Stage stage) { 
     final ComboBox<String> combo = new ComboBox<>(); 

     combo.setValue(Font.getDefault().getFamily()); 
     combo.getItems().setAll(Font.getFamilies()); 
     combo.getStylesheets().add(
       getClass().getResource(
         "combo-size.css" 
       ).toExternalForm() 
     ); 

     StackPane layout = new StackPane(combo); 
     layout.setPadding(new Insets(10)); 

     stage.setScene(new Scene(layout)); 
     stage.show(); 
    } 
} 
+0

不错!有关它的奇怪之处:不能用'-fx-max-width'工作,也不能在组合框本身设置首选宽度的情况下工作。 – isnot2bad

4

(的jewelsea)的解决方案是行不通的我第一次,所以这里是我的解决方案,如果有人需要变通。我只提供了一个自定义单元工厂,并且我可以访问父级ListView并在其中设置maxWidth。

combo.setCellFactory(new Callback<ListView<T>, ListCell<T>>() { 

     @Override 
     public ListCell<T> call(ListView<T> param) { 
      ListCell cell = new ListCell<T>() { 
       @Override 
       public void updateItem(T item, boolean empty) { 
        super.updateItem(item, empty); 

        getListView().setMaxWidth(LIST_VIEW_MAX_HEIGHT); 
        if (!empty) { 
         setText(converter.toString(item)); 
        } else { 
         setText(null); 
        } 
       } 
      }; 
      return cell; 
     } 
    });