How to programmatically set a string value in a JavaFX ComboBox - java

Basically, here is what I need:
I have a JavaFX ComboBox, and it is set to Editable. Since it is editable, there is a little text field in there where someone can enter in a String. I want to use previously generated data to populate that little text field. How do I accomplish this?
enterSchoolName.setSelectionModel((SingleSelectionModel<String>) FXCollections.observableArrayList(studentData.getSchoolName()));
This is all i have in the way of relevant code and an "attempt" at a solution.

You can set the data items of a ComboBox in the constructor:
ObservableList<String> data = FXCollections.observableArrayList("text1", "text2", "text3");
ComboBox<String> comboBox = new ComboBox<>(data);
or later:
comboBox.setItems(data);
To select a data item, you can select the appropriate index in the SelectionModel or the item itself:
comboBox.getSelectionModel().select(0);
comboBox.getSelectionModel().select("text1");
It's also possible to set a value to the combobox editor, which is not contained in the underlying datamodel:
comboBox.setValue("textXXX");

The "little text field" in a editable ComboBox is known as the editor of the ComboBox. And it's a normal TextField object. To access that object, you need to use the method ComboBox#getEditor(). This way you can use the methods of the TextField class. If I understand you correctly, all you want to do is set the text of that TextField.
This is done by doing comboBox.getEditor().setText(text) or comboBox.setValue(text). Both of these methods will set the text of the ComboBox.
But there's a difference when you want to fetch that text. ComboBox#getValue() ComboBox#getEditor()#getText() doesn't necessarily return the same value.
Consider the following example:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestComboBox extends Application {
#Override
public void start(Stage stage) {
ComboBox<String> comboBox = new ComboBox<String>();
comboBox.setEditable(true);
comboBox.setValue("Test");
comboBox.getItems().addAll("Test", "Test2", "Test3");
VBox content = new VBox(5);
content.getChildren().add(comboBox);
content.setPadding(new Insets(10));
GridPane valueGrid = new GridPane();
Label cbValue = new Label();
cbValue.textProperty().bind(comboBox.valueProperty());
Label cbText = new Label();
cbText.textProperty().bind(comboBox.getEditor().textProperty());
valueGrid.add(new Label("ComboBox value: "), 0, 0);
valueGrid.add(new Label("ComboBox text: "), 0, 1);
valueGrid.add(cbValue, 1, 0);
valueGrid.add(cbText, 1, 1);
content.getChildren().add(valueGrid);
stage.setScene(new Scene(content));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
If you change the text in the ComboBox by chosing an alternative in the list, both ComboBox#valueProperty() and ComboBox#getEditor#textProperty() changes. But as you can see if you type something into the ComboBox, only the textProperty changes.
So use whichever method you want when you set the text of the ComboBox, but be aware of the difference when you want to retrieve that text.

Related

How to maniupulate the population of the Controls in JavaFX?

I have this view designed via Scene Builder for JavaFX. There are 4 ComboBox in it. I would like to have the possibility to have something to let the user choose how many and which ComboBox use.
For example, my aim is having 3 modes:
allow the user to use all the 4 ComboBox;
allow the user to use only one ComboBox and let him choose it;
allow the user to use only two ComboBox and let them choose the preferred combination of the four Controls
Any design or idea (and its implementation) are well welcomed since I am not having a very good solution at this moment. I was thinking something like using the CheckBox element near to every ComboBox to enable or disable them, but anyway it is not very good. Also I was thinking about putting 3 Buttons to select the 3 modes and dynamically populate my Container, but I do not know where to start with the implementation.
If you want to let the user select a specific ComboBox, you can enable it using the JavaFX function setDisable() that is on all classes that inherit from the Node class.
(See difference between: setDisabled() vs setDisable())
In the case below, I bind the disabledProperty() to the inverse selectedProperty() on each CheckBox. This way you can select specific ComboBoxes to choose from. Hopefully this will get you started on seeing how JavaFX bindings work.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Test extends Application
{
public static void main(String[] args){
launch(args);
}
#Override
public void start (Stage primaryStage) throws Exception {
VBox vBox = new VBox();
HBox hBox1 = generateComboBoxHBox();
HBox hBox2 = generateComboBoxHBox();
HBox hBox3 = generateComboBoxHBox();
HBox hBox4 = generateComboBoxHBox();
vBox.getChildren().addAll(hBox1, hBox2, hBox3, hBox4);
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
}
// Create 4 of the same HBoxes for an example. Each HBox has a checkbox and combobox
private HBox generateComboBoxHBox(){
HBox hBox = new HBox();
CheckBox checkBox = new CheckBox();
ComboBox<String> comboBox = new ComboBox<>(FXCollections.observableArrayList("Option1", "Option2", "Option3", "Option4"));
comboBox.disableProperty().bind(checkBox.selectedProperty().not());
hBox.getChildren().addAll(checkBox, comboBox);
return hBox;
}
}

Creating a Autocomplete search form in javafx

To get an idea of what I want
When the textfield is clicked, the dropdown appears with suggestions that are filtered out as the user types in the text field. The height of the box should also adjust real-time to either contain all of the items, or a maximum of 10 items.
I managed to get this somewhat working using a ComboBox, but it felt a bit rough around the edges and it didn't seem possible to do what I wanted (The dropdown doesn't resize unless you close it and re-open it).
New idea, have a text field and then show a VBox of buttons as the dropdown. The only problem is that I don't know how to position the dropdown so that it doest stay in the noral flow so it can overlay any exisiting elements below the text field. Any ideas?
Please consider this Example, you can take the idea and apply it to your project.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SearchFormJavaFX extends Application{
#Override
public void start(Stage ps) throws Exception {
String[] options = {"How do I get a passport",
"How do I delete my Facebook Account",
"How can I change my password",
"How do I write some code in my question :D"};
// note that you don't need to stick to these types of containers, it's just an example
StackPane root = new StackPane();
GridPane container = new GridPane();
HBox searchBox = new HBox();
////////////////////////////////////////////////////
TextField text = new TextField();
// add a listener to listen to the changes in the text field
text.textProperty().addListener((observable, oldValue, newValue) -> {
if(container.getChildren().size()>1){ // if already contains a drop-down menu -> remove it
container.getChildren().remove(1);
}
container.add(populateDropDownMenu(newValue, options),0,1); // then add the populated drop-down menu to the second row in the grid pane
});
// those buttons just for example
// note that you can add action listeners to them ..etc
Button close = new Button("X");
Button search = new Button("Search");
searchBox.getChildren().addAll(text,close,search);
/////////////////////////////////////////////////
// add the search box to first row
container.add(searchBox, 0, 0);
// the colors in all containers only for example
container.setBackground(new Background(new BackgroundFill(Color.GRAY, null,null)));
////////////////////////////////////////////////
root.getChildren().add(container);
Scene scene = new Scene(root, 225,300);
ps.setScene(scene);
ps.show();
}
// this method searches for a given text in an array of Strings (i.e. the options)
// then returns a VBox containing all matches
public static VBox populateDropDownMenu(String text, String[] options){
VBox dropDownMenu = new VBox();
dropDownMenu.setBackground(new Background(new BackgroundFill(Color.GREEN, null,null))); // colors just for example
dropDownMenu.setAlignment(Pos.CENTER); // all these are optional and up to you
for(String option : options){ // loop through every String in the array
// if the given text is not empty and doesn't consists of spaces only, as well as it's a part of one (or more) of the options
if(!text.replace(" ", "").isEmpty() && option.toUpperCase().contains(text.toUpperCase())){
Label label = new Label(option); // create a label and set the text
// you can add listener to the label here if you want
// your user to be able to click on the options in the drop-down menu
dropDownMenu.getChildren().add(label); // add the label to the VBox
}
}
return dropDownMenu; // at the end return the VBox (i.e. drop-down menu)
}
public static void main(String[] args) {
launch();
}
}
What you're trying to do has already been implemented, and is included in ControlsFx. It's open source, and I think it would suit you need. It looks some what like this
You can even add custom nodes to it, so that cross can be done too.
public void pushEmails(TextField Receptient) {
ArrayList<CustomTextField> list = new ArrayList<>();
for (int i = 0; i < Sendemails.size(); i++) {
CustomTextField logo=new CustomTextField(Sendemails.get(i));
ImageView logoView=new ImageView(new Image("/Images/Gmail.png"));
logo.setRight(logoView);
list.add(logo);
}
TextFields.bindAutoCompletion(Receptient, list);
}

JavaFX ComboBox plus ListView for Map of Sets

I have an ObservableMap<String, ObservableSet<String>>.
I would like to create a UI which has a comboBox and a ListView. The comboBox is populated by the keys of the map. Selecting one key from the map would then populate the ListView with the contents of the Set that is mapped to by that key.
In the past I have handled making a ListView for an ObservableSet by creating a second data structure, an ObservableList, and adding a ChangeListener to the set that updates the ObservableList so that it mirrors the set.
However in this case I don't have just one set, but a map of many sets. See my previous question which is similar but simpler: JavaFX: Populate TableView with an ObservableMap that has a custom class for its values
Here is some sample runnable code. It provides most of the functionality I want. However, the ListView doesn't respond to changes in the underlying Map of Sets. In this example, if you select "Vehicles" from the ComboBox and then click the Change Vehicles button, no changes are reflected in the ListView. However if you then select "Colors" and then back to "Vehicles", the ListView is repopulated and you now see the change.
So how would one get the ListView to automatically update itself when the underlying Map of Sets changes? My first guess is that you need to add a Listener to each Set that maintains a mirror of the contents of each Set in an ObservableList. But since this is a Map of Sets, the number of Sets can change and so the number of mirroring Lists will need to change. So I would need to have a collection of ObservableLists, I suppose...? And every time a new element is added to the Map, a new Listener and new ObservableList will need to be constructed.
import java.util.Map;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MapSetView extends Application {
ObservableMap<String, ObservableSet<String>> map = FXCollections.observableHashMap();
ComboBox<String> keysCombo = new ComboBox<>();
ListView<String> valuesList = new ListView<>();
#Override
public void start(Stage stage) throws Exception {
map.put("Vehicle", FXCollections.observableSet("plane", "train", "automobile"));
map.put("Color", FXCollections.observableSet("black","blue","red"));
keysCombo.getItems().clear();
for(Map.Entry<String, ObservableSet<String>> varEntry : map.entrySet()) {
keysCombo.getItems().add(varEntry.getKey());
}
keysCombo.setOnAction( (ActionEvent e) -> {
String selectedName = keysCombo.getSelectionModel().getSelectedItem();
valuesList.setItems(FXCollections.observableArrayList(map.get(selectedName)));
});
Button changeVehicles = new Button("Change Vehicles");
changeVehicles.setOnAction( (ActionEvent e) -> {
map.get("Vehicle").add("boat");
});
// display UI
VBox vBox = new VBox(8);
vBox.getChildren().addAll(keysCombo, valuesList, changeVehicles);
Scene scene = new Scene(vBox, 400, 400);
stage.setScene(scene);
stage.show();
}
}

Automatically adjust the width of a JavaFX TextArea

So, I've been working on a dynamical UI, which consists of TextAreas, but the thing is that the inputs to TextAreas come from the database and therefore are with different lengths. And I must also make the TextAreas dynamic depending on the length of the strings from database. And this is a difficult task because the length of the strings doesn't automatically tell its length in pixels.
So, for example strings:
a)"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"
b)"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
Those two strings consist of 70 letters but their length in pixels is completely different.
And I need to make sure that the TextArea gets its width based on the string's length in pixels.
I have tried to use something like this:
int textwidth = (int) font.getStringBounds(ta.getText(), frc).getWidth();
But it gives me errors, because the font is the following:
textLabel.getFont()
-> Font[name=System Regular, family=System, style=Regular, size=12.0]
But using this font in the previous getStringBounds method it gives me errors:
Cannot resolve method 'getStringBounds(java.lang.String, java.awt.font.FontRenderContext)'
Any help would be highly appriciated. I can provide more information if required.
Thanks in advance!
You can measure the size of some text by creating a Text object, placing it in a pane (e.g. a StackPane) and calling layout() on the pane, then get the layout bounds of the text. Set the font to the same font as you want to use in the text area.
The only remaining issue is that the text area needs some padding for its border, etc, the following code example just uses a fixed padding (established via trial-and-error) but works well enough. You can probably improve on this if needed.
Type something in the text field and press enter; it will update the text and size of the text area:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class SizeTextAreaToString extends Application {
#Override
public void start(Stage primaryStage) {
TextField enterField = new TextField();
TextArea textArea = new TextArea();
textArea.setPrefRowCount(1);
enterField.setOnAction(e -> sizeTextAreaToText(textArea, enterField.getText()));
VBox root = new VBox(5, enterField, textArea);
VBox.setVgrow(textArea, Priority.NEVER);
root.setPadding(new Insets(5));
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
private void sizeTextAreaToText(TextArea textArea, String text) {
Text t = new Text(text);
t.setFont(textArea.getFont());
StackPane pane = new StackPane(t);
pane.layout();
double width = t.getLayoutBounds().getWidth();
double padding = 20 ;
textArea.setMaxWidth(width+padding);
textArea.setText(text);
}
public static void main(String[] args) {
launch(args);
}
}

JavaFX: Make node take no space, but let its parent decide its position

I have a TextField and a ListView. As the user types in the TextField, suggestions come up in the ListView:
When the TextField is empty, the ListView disappears, by setting the visible and managed properties to false.
However, when the user starts to type, the ListView takes up space and pushes everything down. Using .setManaged(false) allows it not to take up any space, but it doesn't display anymore, as I haven't defined a position for it. I have tried setting the layoutX and layoutY of the search list, but it still doesn't display.
Ideally I'd like the ListView's position to be affected by the layout but not to take up any space.
Any ideas?
Wrap the container that holds the text field(s) in an AnchorPane. Add the ListView to the AnchorPane after the text field container (so it stays on top). Then you need to position the ListView appropriately relative to the text field when you make it visible; I think the best way to do this is to first convert the bounds of the text field from local coordinates to Scene coordinates, then convert those bounds to the coordinates relative to the AnchorPane.
Here's an SSCCE:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class SuggestionList extends Application {
#Override
public void start(Stage primaryStage) {
AnchorPane root = new AnchorPane();
ListView<String> suggestionBox = new ListView<>();
suggestionBox.getItems().addAll("Here", "Are", "Some", "Suggestions");
suggestionBox.setMaxHeight(100);
suggestionBox.setVisible(false);
// Grid pane to hold a bunch of text fields:
GridPane form = new GridPane();
for (int i=0; i<10; i++) {
form.addRow(i, new Label("Enter Text:"), createTextField(suggestionBox));
}
// just move the grid pane a little to test suggestion box positioning:
AnchorPane.setLeftAnchor(form, 20.0);
AnchorPane.setRightAnchor(form, 20.0);
AnchorPane.setTopAnchor(form, 20.0);
AnchorPane.setBottomAnchor(form, 20.0);
// allows focus on grid pane, so user can click on it to remove focus from text field.
form.setFocusTraversable(true);
root.setPadding(new Insets(20));
root.getChildren().addAll(form, suggestionBox);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private TextField createTextField(ListView<String> suggestionBox) {
TextField textField = new TextField();
ChangeListener<String> selectionListener = (obs, oldItem, newItem) -> {
if (newItem != null) {
textField.setText(newItem);
}
};
textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
if (isNowFocused) {
suggestionBox.setVisible(true);
// compute bounds of text field relative to suggestion box's parent:
Parent parent = suggestionBox.getParent(); // (actually the anchor pane)
Bounds tfBounds = textField.getBoundsInLocal();
Bounds tfBoundsInScene = textField.localToScene(tfBounds);
Bounds tfBoundsInParent = parent.sceneToLocal(tfBoundsInScene);
// position suggestion box:
suggestionBox.setLayoutX(tfBoundsInParent.getMinX());
suggestionBox.setLayoutY(tfBoundsInParent.getMaxY());
suggestionBox.setPrefWidth(tfBoundsInParent.getWidth());
suggestionBox.getSelectionModel().selectedItemProperty().addListener(selectionListener);
} else {
suggestionBox.setVisible(false);
suggestionBox.getSelectionModel().selectedItemProperty().removeListener(selectionListener);
}
});
textField.setOnAction(event -> {
suggestionBox.setVisible(false);
suggestionBox.getSelectionModel().selectedItemProperty().removeListener(selectionListener);
});
return textField ;
}
public static void main(String[] args) {
launch(args);
}
}
You might be able to use similar positional tricks and just add it to the same scene, with managed set to false.

Categories

Resources