How to get focus on TextField within TabPane, when Enter Key is pressed (using Javafx)? - javafx

How to requestFocus on TextField of different Tabs of TabPane, whenever the Enter Key is pressed on that particular Tab.
Each Tab within TabPane contains TextField, whenever a particular Tab is selected using Enter Key, than the TextField within that Tab must get Focused (requestFocus)
package tabdemo;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TabDemo extends Application {
#Override
public void start(Stage primaryStage) {
TabPane tabPane = new TabPane();
tabPane.setPrefHeight(500);
VBox.setVgrow(tabPane, Priority.ALWAYS);
tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
tabPane.setStyle("-fx-background-color: #fff; -fx-border-color: #e7eaec #e7eaec #e7eaec #e7eaec; -fx-border-width: 6;");
Tab tab1 = new Tab();
tab1.setText(" Try Demo");
tab1.setId("TryDemo");
TextField username1 = new TextField();
tab1.setContent(username1);
Tab tab2 = new Tab();
tab2.setText(" Select Company");
tab2.setId("SelectCompany");
TextField username2 = new TextField();
tab2.setContent(username2);
Tab tab3 = new Tab();
tab3.setText(" Create Company");
tab3.setId("CreateCompany");
TextField username3 = new TextField();
tab3.setContent(username3);
//Add childen to tabpane
tabPane.getTabs().addAll(tab1, tab2, tab3);
StackPane root = new StackPane();
root.getChildren().add(tabPane);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
// Tabpane Change Listener
tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
#Override
public void changed(ObservableValue<? extends Tab> arg0, Tab oldtab, Tab newtab) {
if (newtab == tab1) {
}
if (newtab == tab2) {
}
if (newtab == tab3) {
//tab3.getContent().requestFocus();
//username3.requestFocus();
}
}
});
// End Tabpane Change Listener
// Root Listner
root.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.TAB || event.getCode() == KeyCode.ENTER) {
tabPane.requestFocus();
event.consume();
}
}
});
// END Root Listner
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Any help would be appreciated.

Change your implementation of the ChangeListener to this:
// Tabpane Change Listener
tabPane.getSelectionModel().selectedItemProperty().addListener((arg0, oldtab, newtab) -> {
TextField field = (TextField) newtab.getContent();
Platform.runLater(() -> field.requestFocus());
});
This ensures that the request for the focus is pushed as the last 'task' for the application thread.
See also RequestFocus in TextField doesn't work -JavaFX 2.1 and JavaFX: Focusing textfield programmatically

Related

How to stop transition when checkbox is unchecked javafx

So I've made a checkbox that applies a scale transition to a rectangle when checked. But the problem is that the transition keeps going even after I uncheck the checkbox. Any ideas on how to make it stop after un-checking?
checkbox.setOnAction(e -> {
ScaleTransition scaleT = new ScaleTransition(Duration.seconds(5), rectangle);
scaleT.setAutoReverse(true);
scaleT.setCycleCount(Timeline.INDEFINITE);
scaleT.setToX(2);
scaleT.setToY(2);
scaleT.play();
});
To control the animation, you need to define the transistion(with INDEFINITE cycle count) outside the CheckBox listener/action. Then you can just play/pause the animation as you required.
Below is the quick demo:
import javafx.animation.ScaleTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ScaleTransitionDemo extends Application {
#Override
public void start(Stage stage) {
Shape rectangle = new Rectangle(50, 50, Color.BLUE);
ScaleTransition transition = new ScaleTransition(Duration.seconds(1), rectangle);
transition.setDuration(Duration.seconds(1));
transition.setAutoReverse(true);
transition.setCycleCount(Timeline.INDEFINITE);
transition.setToX(3);
transition.setToY(3);
CheckBox checkBox = new CheckBox("Animate");
checkBox.selectedProperty().addListener((obs, old, selected) -> {
if (selected) {
transition.play();
} else {
transition.pause();
}
});
StackPane pane = new StackPane(rectangle);
VBox.setVgrow(pane, Priority.ALWAYS);
VBox root = new VBox(20, checkBox, pane);
root.setPadding(new Insets(10));
Scene scene = new Scene(root, 300, 300);
stage.setScene(scene);
stage.setTitle("Scale transition");
stage.show();
}
public static void main(String[] args) {
launch();
}
}
checking whether checkbox is selected or not with .isSelected() method . In this approach , scaled node will back to xy = 1 scale if checkbox is unchecked , but it will be disabled until transition ends .You can adjust setDuration . I've changed it just for gif recording. This is a single class javafx app you can try .
App.java
public class App extends Application {
#Override
public void start(Stage stage) {
Shape rectangle = new Rectangle(50, 50, Color.BLUE);
ScaleTransition scaleT = new ScaleTransition(Duration.seconds(1), rectangle);
CheckBox checkBox = new CheckBox("scale");
checkBox.setOnAction(e -> {
if (checkBox.isSelected()) {
scaleT.setDuration(Duration.seconds(1));
scaleT.setAutoReverse(true);
scaleT.setCycleCount(Timeline.INDEFINITE);
scaleT.setToX(2);
scaleT.setToY(2);
scaleT.play();
} else {
scaleT.setDuration(scaleT.getCurrentTime());
scaleT.stop();
scaleT.setCycleCount(1);
scaleT.setToX(1);
scaleT.setToY(1);
scaleT.play();
checkBox.setDisable(true);
scaleT.setOnFinished((t) -> {
checkBox.setDisable(false);
});
}
});
var scene = new Scene(new HBox(50, rectangle, checkBox), 640, 480);
stage.setScene(scene);
stage.setTitle("scale transition");
stage.show();
}
public static void main(String[] args) {
launch();
}
}

How do I show contents from the password field in javafx using checkbox [duplicate]

This question already has answers here:
How to unmask a JavaFX PasswordField or properly mask a TextField?
(7 answers)
Closed 3 years ago.
Im a student studying java and javafx, how do I show the password in the passwordfield using a checkbox? I am using gluon scenebuilder as my fxml editor
The duplicate is listed above for the correct but more complicated way of doing this. In this answer, I am showing two examples. One with a CheckBox and the other with the all-seeing eye. The eye is to use a StackPane to layer the node. For the CheckBox solution, put a TextField and then a PasswordField in the StackPane. Bring the TextField toFront when the CheckBox is checked and set its text using the PasswordField. Clear the TextField when the CheckBox is not checked and move the PasswordField toFront. For the All-seeing eye example, use the same ideas but add an ImageView and always keep the ImageView toFront.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestingGround extends Application
{
Image image = new Image("https://previews.123rf.com/images/andrerosi/andrerosi1905/andrerosi190500216/123158287-eye-icon-vector-look-and-vision-icon-eye-vector-icon.jpg");
#Override
public void start(Stage primaryStage)
{
HBox passwordControl1 = createPasswordFieldWithCheckBox();
HBox passwordControl2 = createPasswordFieldWithCheckBox();
StackPane passwordControl3 = createPasswordFieldWithEye();
StackPane passwordControl4 = createPasswordFieldWithEye();
VBox root = new VBox(passwordControl1, passwordControl2, passwordControl3, passwordControl4);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
HBox createPasswordFieldWithCheckBox()
{
PasswordField passwordField = new PasswordField();
passwordField.setPrefHeight(50);
TextField textField = new TextField();
textField.setPrefHeight(50);
passwordField.textProperty().bindBidirectional(textField.textProperty());
StackPane stackPane = new StackPane(textField, passwordField);
CheckBox checkBox = new CheckBox();
checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
textField.toFront();
}
else {
passwordField.toFront();
}
});
HBox root = new HBox(stackPane, checkBox);
root.setSpacing(5);
root.setAlignment(Pos.CENTER);
return root;
}
StackPane createPasswordFieldWithEye()
{
PasswordField passwordField = new PasswordField();
passwordField.setPrefHeight(50);
TextField textField = new TextField();
passwordField.textProperty().bindBidirectional(textField.textProperty());
textField.setPrefHeight(50);
ImageView imageView = new ImageView(image);
imageView.setFitHeight(32);
imageView.setFitWidth(32);
StackPane.setMargin(imageView, new Insets(0, 10, 0, 0));
StackPane.setAlignment(imageView, Pos.CENTER_RIGHT);
imageView.setOnMousePressed((event) -> {
textField.toFront();
imageView.toFront();
});
imageView.setOnMouseReleased((event) -> {
passwordField.toFront();
imageView.toFront();
});
StackPane root = new StackPane(textField, passwordField, imageView);
return root;
}
}
You could use a custom Tooltip to show the password:
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class FxMain extends Application {
private SimpleBooleanProperty showPassword ;
private CheckBox checkBox;
private Tooltip toolTip;
private PasswordField pF;
private Stage stage;
#Override
public void start(Stage stage) {
this.stage = stage;
showPassword = new SimpleBooleanProperty();
showPassword.addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> {
if(newValue){
showPassword();
}else{
hidePassword();
}
});
final Label message = new Label("");
Label label = new Label("Password");
toolTip = new Tooltip();
toolTip.setShowDelay(Duration.ZERO);
toolTip.setAutoHide(false);
toolTip.setMinWidth(50);
pF = new PasswordField();
pF.setOnKeyTyped(e -> {
if ( showPassword.get() ) {
showPassword();
}
});
HBox hb = new HBox(10, label, pF);
hb.setAlignment(Pos.CENTER_LEFT);
checkBox = new CheckBox("Show password");
showPassword.bind(checkBox.selectedProperty());
VBox vb = new VBox(10, hb, checkBox, message);
vb.setPadding(new Insets(10));
stage.setScene(new Scene(vb,300,100));
stage.show();
}
private void showPassword(){
Point2D p = pF.localToScene(pF.getBoundsInLocal().getMaxX(), pF.getBoundsInLocal().getMaxY());
toolTip.setText(pF.getText());
toolTip.show(pF,
p.getX() + stage.getScene().getX() + stage.getX(),
p.getY() + stage.getScene().getY() + stage.getY());
}
private void hidePassword(){
toolTip.setText("");
toolTip.hide();
}
public static void main(String[] args) {
launch(args);
}
}

How to select the next text field after a key pressed (ENTER) in javafx?

I am making a login GUI and after I enter the username, I want to hit ENTER key and it will select the password text field. How can I achieve this?
My attempt:
#FXML
void userNameKeyPressed(KeyEvent event) {
if(event.getCode() == KeyCode.ENTER || event.getCode() == KeyCode.TAB) {
passWord.requestFocus();
}
}
I think you'll need to compile a more complete example. Eg maybe a simple fxml and where it goes wrong. Here is an example that works, and it uses most of the ingredients you are.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.input.KeyEvent;
public class TextFields extends Application{
public static void main(String[] args){
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("text field");
TextField a = new TextField();
TextField b = new TextField();
a.setOnKeyPressed( evt ->{
System.out.println(KeyCode.ENTER + ", " + evt.getCode());
if(evt.getCode().equals(KeyCode.ENTER)){
System.out.println("entered");
b.requestFocus();
}
});
BorderPane root = new BorderPane();
root.setLeft(a);
root.setRight(b);
primaryStage.setScene(new Scene(root, 300, 100));
primaryStage.show();
}
}
This code creates a frame with 2 text fields, if you press enter in the left one, you will move to the right one.

Javafx add a dropdown event listener for choicebox

I have a ChoiceBox and I want to refresh it's content whenever user expands it. I haven't found a proper listener for this. All the stuff google gives is related to handling ChangeValue events.
I reckon I should add eventListener<ActionEvent> to ChoiceBox since what I'm handling is click on a ChoiceBox, but my implementation doesn't work.
ActionEvent fires when I click on any List value, not when I click ChoiceBox itself.
Register a listener with the choice box's showingProperty:
choiceBox.showingProperty().addListener((obs, wasShowing, isNowShowing) -> {
if (isNowShowing) {
// choice box popup is now displayed
} else {
// choice box popup is now hidden
}
});
Here is a quick demo:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ChoiceBoxPopupTest extends Application {
private int nextValue ;
#Override
public void start(Stage primaryStage) {
ChoiceBox<Integer> choiceBox = new ChoiceBox<>();
choiceBox.getItems().add(nextValue);
choiceBox.setValue(nextValue);
choiceBox.showingProperty().addListener((obs, wasShowing, isNowShowing) -> {
if (isNowShowing) {
choiceBox.getItems().setAll(++nextValue, ++nextValue, ++nextValue);
}
});
BorderPane root = new BorderPane();
root.setTop(choiceBox);
BorderPane.setAlignment(choiceBox, Pos.CENTER);
root.setPadding(new Insets(5));
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

How to generate rectangle with user values in output?

I have seen examples of Rectangle in JavaFx. But Please can anybody Provide me the example where in output window/Scene, if user put desirable width and height, rectangle should be generated automatically.
here is my example
VBox vb = new VBox(20);
HBox h1 = new HBox(7);
HBox h2 = new HBox(7);
Label lebel1 = new Label("X:");
Label lebel2 = new Label("Y:");
TextField txt1 = new TextField();
TextField txt2 = new TextField();
//Converting textfield to integer only
ChangeListener<String> forceNumberListener = (observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*"))
((StringProperty) observable).set(oldValue);
};
txt1.textProperty().addListener(forceNumberListener);
txt2.textProperty().addListener(forceNumberListener);
double width = Double.parseDouble(txt1.getText());
double height = Double.parseDouble(txt2.getText());
Rectangle rect1 = new Rectangle();
rect1.setHeight(height);
rect1.setWidth(width);
h1.getChildren().addAll(lebel1, txt1);
h2.getChildren().addAll(lebel2, txt2);
vb.getChildren().addAll(h1,h2,rect1);
If user put any integer value in "x" as width, "y" as height, Rectangle should be generated below fields. but this code is wrong and i don't know other methods. Please
Thank you so much
You should use the TextField's onkeyreleased event handler. In this app, if both TextFields have a number typed in, a rectangle will be generated. Both TextFields have an event handler that does the same thing if one of their text is changed. This does not catch for any non-double values.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication104 extends Application
{
#Override
public void start(Stage primaryStage)
{
BorderPane root = new BorderPane();
VBox vbox = new VBox();
vbox.setMinWidth(100);
TextField textfield1 = new TextField();
TextField textfield2 = new TextField();
textfield1.setPrefWidth(50);
textfield1.setPromptText("Enter height");
textfield1.setOnKeyReleased(new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent event)
{
if(textfield1.getText().length() > 0 && textfield2.getText().length() > 0)
{
Rectangle rectangle = new Rectangle();
rectangle.setHeight(Double.parseDouble(textfield1.getText()));
rectangle.setWidth(Double.parseDouble(textfield2.getText()));
rectangle.setFill(Color.BLUE);
root.setCenter(rectangle);
}
}
});
textfield2.setPrefWidth(100);
textfield2.setPromptText("Enter length");
textfield2.setOnKeyReleased(new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent event)
{
if(textfield1.getText().length() > 0 && textfield2.getText().length() > 0)
{
Rectangle rectangle = new Rectangle();
rectangle.setHeight(Double.parseDouble(textfield1.getText()));
rectangle.setWidth(Double.parseDouble(textfield2.getText()));
rectangle.setFill(Color.BLUE);
root.setCenter(rectangle);
}
}
});
vbox.getChildren().addAll(textfield1, textfield2);
root.setLeft(vbox);
Scene scene = new Scene(root, 500, 500);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}

Resources