I started learning JavaFx, so I decided to do a little practical project to prove my knowledge. As a result of that I come to the situation, where I search for a possibility to easily disable e.g: a button until, other previous input controls (e.g: textfield) are correctly filled.
I already know event listeners in JavaFx or in Java at all, but im not sure about how to implement an event listener, which solves my problem.
I searched for a solution, but I didn't find one, so hopefully there's someone out there which has an idea how to solve it.
So far,
Daniel
EventListener's aren't the correct way to handle disabling buttons and other controls based on the status of other nodes on the screen. You should use Bindings. Here's a sample screen with two TextFields. The top one needs to just be non empty, and the bottom one needs to have a numeric value in it for the button to be enabled. For those who dislike disabled buttons, I've added a Text with an error message at the bottom, and its visibility is linked to the enabled/disabled status of the button:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class ButtonDisable extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
TextField textField1 = new TextField();
TextField textField2 = new TextField();
Button button = new Button("Click Me");
Text errorText = new Text("Field 1 must have a value, Field 2 must have a numeric value");
button.disableProperty()
.bind(Bindings.createBooleanBinding(() -> checkTextfields(textField1.getText(), textField2.getText()),
textField1.textProperty(),
textField2.textProperty()));
errorText.visibleProperty().bind(button.disabledProperty());
primaryStage.setScene(new Scene(new VBox(10, textField1, textField2, button, errorText), 400, 200));
primaryStage.show();
}
private boolean checkTextfields(String text1, String text2) {
return (text1.isEmpty() || !isNumeric(text2));
}
private static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
Related
I thought I found the answer with deselect() but strangely it doesn't do anything, the text is still all selected on opening.
TextInputDialog textInput = new TextInputDialog("whatever text");
textInput.initOwner(sentence.stage);
Optional<String> result = textInput.showAndWait();
if (result.isPresent()) {
// process
}
textInput.getEditor().deselect();
The Dialog#showAndWait() method does not return until the dialog is closed. That means your call to deselect() is too late. However, simply reordering your code does not appear to solve your problem. This looks like a timing issue; the text is probably selected when the field gains focus so you need to deselect the text after that happens. For example:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
var button = new Button("Show dialog...");
button.setOnAction(
ae -> {
var textInput = new TextInputDialog("Some text");
textInput.initOwner(primaryStage);
Platform.runLater(textInput.getEditor()::deselect);
textInput.showAndWait();
});
var root = new StackPane(button);
primaryStage.setScene(new Scene(root, 500, 300));
primaryStage.show();
}
}
The Runnable passed to runLater is executed after the dialog is shown and after the text has been selected.
I want to bind a CheckMenuItem's selectedProperty to another observable value, like cmi.selectedProperty().bind(myObs). However, this is not possible, since the framework sets the selection property when the check menu item is clicked (see line 1394 of ContextMenuContent.java).
Is there a way to intercept the click—so that I can do my own custom processing—and still bind the selection property to another observable?
I suppose I'm thinking of the click as a request to update some state. The user clicks the menu item, then the program attempts to change some state accordingly, and the selection changes if the state successfully updated. Under 'normal' conditions, the check should toggle upon every click; however, if something bad happens, I'd prefer that the check doesn't toggle and instead reflects the true state of the program.
One way to do this (without getting into writing a skin for the menu item) is to roll your own menu item with a graphic. You can just use a region for the graphic and steal the CSS from the standard modena stylesheet. Then bind the visible property of the graphic to the observable value, and toggle the observable value in the menu item's action handler:
import java.util.Random;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
public class VetoableMenuItemWithCheck extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
MenuBar menuBar = new MenuBar() ;
Menu choices = new Menu("Choices");
// observable boolean value to which we're going to bind:
BooleanProperty selected = new SimpleBooleanProperty();
// graphic for displaying checkmark
Region checkmark = new Region();
checkmark.getStyleClass().add("check-mark");
// bind visibility of graphic to observable value:
checkmark.visibleProperty().bind(selected);
MenuItem option = new MenuItem("Option", checkmark);
choices.getItems().add(option);
Random rng = new Random();
// when menu item action occurs, randomly fail (with error alert),
// or update boolean property (which will result in toggling check mark):
option.setOnAction(e -> {
if (rng.nextDouble() < 0.25) {
Alert alert = new Alert(AlertType.ERROR, "I'm sorry Dave, I'm afraid I can't do that", ButtonType.OK);
alert.showAndWait();
} else {
selected.set(! selected.get());
}
});
menuBar.getMenus().add(choices);
root.setTop(menuBar);
Scene scene = new Scene(root, 400, 400);
scene.getStylesheets().add("check-menu.css");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
and
check-menu.css:
.check-mark {
-fx-background-color: -fx-mark-color;
-fx-shape: "M0,5H2L4,8L8,0H10L5,10H3Z";
-fx-scale-shape: false;
-fx-padding: 0em 0.11777em 0em 0em;
}
There may be a simpler approach, but this seems not too bad.
A version for a vetoable radio menu item could follow the same basic idea, but with
ObjectProperty<MenuItem> selectedItem = new SimpleObjectProperty<>();
and then for each menu item do
checkmark.visibleProperty().bind(selectedItem.isEqualTo(option));
option.setOnAction(e -> {
if (successful()) {
selectedItem.set(option);
}
});
I have a JavaFX application that has various TextField widgets in the main frame. I have a MenuBar that includes the MenuItem objects "Copy" and "Paste" like a standard production application would have. Since any or none of the various TextField objects could be selected at any given time, it seems easier to just hardcode a "Ctrl+C" or "Ctrl+V" key press in the setOnAction events of the "Copy" and "Paste" MenuItem objects rather than use a Clipboard object and loop iterating through all TextFields to find the highlighted text (if any).
Is there a way to hardcode this key press action in Java? I looked into the KeyCombination class but it does not actually trigger the action described by the given key combination.
I think by "Since any or none of the various TextField objects could be selected at any given time" you are referring to which (if any) text field has the keyboard focus.
You can easily get this information from the scene: just do
Node focusOwner = scene.getFocusOwner();
if (focusOwner instanceof TextField) {
TextField textField = (TextField) focusOwner ;
String selectedText = textField.getSelectedText();
// ...
}
Note also that TextInputControl defines a copy() method that copies the selected text to the system clipboard. (Similarly, there's a paste() method too.) So you can leverage those to make the functionality easy.
Here's a SSCCE:
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputControl;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class FocusMenuTest extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
VBox textFields = new VBox(5, new TextField("One"), new TextField("Two"), new TextField("Three"));
MenuBar menuBar = new MenuBar();
Menu edit = new Menu("Edit");
MenuItem copy = new MenuItem("Copy");
copy.setOnAction(e -> {
Node focusOwner = menuBar.getScene().getFocusOwner();
if (focusOwner instanceof TextInputControl) {
((TextInputControl)focusOwner).copy();
}
});
MenuItem paste = new MenuItem("Paste");
paste.setOnAction(e -> {
Node focusOwner = menuBar.getScene().getFocusOwner();
if (focusOwner instanceof TextInputControl) {
((TextInputControl)focusOwner).paste();
}
});
menuBar.getMenus().add(edit);
edit.getItems().addAll(copy, paste);
root.setCenter(textFields);
root.setTop(menuBar);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
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);
}
I'm trying to make a list of boxes which a user can select through with their mouse and when one box is selected, it highlights it with a color, and all the rest of the boxes turn white. Is there an equivalent to the css tag :target in javafx like there is an equivalent to :focus(:focused) or do I have to handle selecting items in a list my own way?
There is no built-in target pseudoclass, but there is an API for creating your own CSS PseudoClass objects.
Here is a simple example:
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.css.PseudoClass;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class SelectableBoxes extends Application {
private static final PseudoClass SELECTED_PSEUDOCLASS = PseudoClass.getPseudoClass("selected");
private ObjectProperty<Pane> selectedBox = new SimpleObjectProperty<>();
#Override
public void start(Stage primaryStage) {
VBox container = new VBox(5);
container.setPadding(new Insets(20));
int numBoxes = 5 ;
for (int i = 0 ; i < numBoxes; i++) {
container.getChildren().add(createBox());
}
ScrollPane scroller = new ScrollPane(container);
Scene scene = new Scene(scroller, 400, 400);
scene.getStylesheets().add("selectable-boxes.css");
primaryStage.setScene(scene);
primaryStage.show();
}
private Pane createBox() {
Pane pane = new Pane();
pane.setMinSize(50, 50);
pane.getStyleClass().add("box");
pane.setOnMouseClicked(e -> selectedBox.set(pane));
selectedBox.addListener((obs, oldSelection, newSelection) ->
pane.pseudoClassStateChanged(SELECTED_PSEUDOCLASS, newSelection == pane));
return pane ;
}
public static void main(String[] args) {
launch(args);
}
}
with the corresponding CSS file selectable-boxes.css:
.box {
-fx-border-width: 1 ;
-fx-border-color: black ;
}
.box:selected {
-fx-background-color: blue ;
}
This "answer" is to provide an alternate solution for the task you wish to accomplish (rather than directly answering your question regarding CSS tags).
For your task, you may wish to use ToggleButtons in a ToggleGroup, or a ListView.
Oracle provide a ToggleButton demo. By default a ToggleButton behaves a bit different from a radio button (e.g. it is possible to have nothing selected). If you want radio button style behavior, to ensure something is always selected, you can use the bit of code at: JDK-8090668
Need TogglePolicy for ToggleButton in ToggleGroup
toggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
if (toggle != null && new_toggle == null) {
toggle.setSelected(true);
}
}
});
The in-built controls can be styled quite extensively using CSS to get custom looks. Refer to the modena.css file for default css styles for the controls which can be overriden.