Reputation: 378
I am currently using JavaFx ComboBox
and I load the options from a XML file.
The problem I have is that some items are too long and they don't fit well:
I have tried using CSS width:
.combo-box {
-fx-pref-width: 300;
}
.combo-box-popup > .list-view {
-fx-pref-width: 300;
}
Is it possible to display ComboBox
items in two lines instead of displaying in one line?
Upvotes: 4
Views: 650
Reputation: 10263
You'll want to setup a custom CellFactory
for your ComboBox
. Within the new ListCell
we build, we can use a simple Label
that wraps the text for us.
Here is a complete example to demonstrate:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ComboBoxTextWrap extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple Interface
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
// The ComboBox
ComboBox<String> comboBox = new ComboBox<>();
// Sample data
comboBox.getItems().addAll(
"Shorty",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"Shorty Jr.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
);
// Create our custom cells for the ComboBox
comboBox.setCellFactory(param -> new ListCell<String>() {
// Create a Label to store our text. We'll set it to wrap text and it's preferred width
final Label label = new Label() {{
setWrapText(true);
setPrefWidth(200);
}};
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
// Add our text to the Label
label.setText(item);
setGraphic(label);
}
}
});
// Add the combobox to the layout
root.getChildren().add(comboBox);
// Show the stage
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("Sample");
primaryStage.show();
}
}
The Result:
Upvotes: 2