JavaFX disable tab navigation - java

I am writing a console application and I would like to autocomplete commands when pressing tab. The problem is that when you press tab in javaFX it switches focus to another element in the application. Any way to disable this?

Add an event filter and consume the event:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class DisableFocusNavigation extends Application {
private TextField createTextField() {
TextField textField = new TextField();
textField.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.TAB) {
System.out.println("Tab pressed");
event.consume();
}
});
return textField ;
}
#Override
public void start(Stage primaryStage) {
TextField tf1 = createTextField();
TextField tf2 = createTextField();
VBox root = new VBox(5, tf1, tf2);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(20));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Note that this isn't particularly good practice, as it makes it impossible to use the application without a mouse (or similar input device). You should at least check for modifier keys in the event filter, and allow for some focus traversal options.

Related

JavaFX TabPane reordering bug, looking for a workaround

I found a little bug in JavaFX TabPane, and am looking for a workaround. I am running JavaFX 13.0.1.
How it happens:
The TabPane's DragPolicy must be set to TabPane.TabDragPolicy.REORDER.
You can navigate between tabs via keyboard shortcuts CTRL + TAB & CTRL + SHIFT + TAB.
However, if I drag, say, the last tab to the very left and release it back to the position it was in (so that nothing should change), these keyboard shortcuts get messed up - no longer pointing to proper next/previous tabs.
You should be able to reproduce it simply with the following code:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Test extends Application {
#Override
public void start(Stage primaryStage) {
TabPane tabPane = new TabPane();
tabPane.setTabDragPolicy(TabPane.TabDragPolicy.REORDER);
tabPane.getTabs().add(new Tab("First"));
tabPane.getTabs().add(new Tab("Second"));
tabPane.getTabs().add(new Tab("Third"));
tabPane.getTabs().add(new Tab("Fourth"));
tabPane.getTabs().add(new Tab("Fifth"));
StackPane root = new StackPane();
root.getChildren().add(tabPane);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("TabPane bug");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
An interesting bug. It appears TabPane.getTabs() returns a List which may or may not reflect the visual ordering of the tabs. But the navigation keys always rely on the getTabs() order, not the visual order.
One workaround is to use a Label as a graphic for each Tab, while leaving the Tab’s text as null. You can then keep the Tabs sorted properly yourself, by checking the visual position of each such Label.
import java.util.List;
import java.util.ArrayList;
import javafx.beans.Observable;
import javafx.geometry.Bounds;
import javafx.geometry.NodeOrientation;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class TabDragTest2 extends Application {
private static Tab createTab(String title) {
Tab tab = new Tab();
tab.setGraphic(new Label(title));
return tab;
}
#Override
public void start(Stage primaryStage) {
TabPane tabPane = new TabPane();
tabPane.setTabDragPolicy(TabPane.TabDragPolicy.REORDER);
tabPane.getTabs().add(createTab("First"));
tabPane.getTabs().add(createTab("Second"));
tabPane.getTabs().add(createTab("Third"));
tabPane.getTabs().add(createTab("Fourth"));
tabPane.getTabs().add(createTab("Fifth"));
tabPane.getTabs().addListener((Observable o) -> {
List<Tab> tabs = new ArrayList<>(tabPane.getTabs());
NodeOrientation orientation = tabPane.getEffectiveNodeOrientation();
boolean ltr = orientation == NodeOrientation.LEFT_TO_RIGHT;
tabs.sort((t1, t2) -> {
Node title1 = t1.getGraphic();
Node title2 = t2.getGraphic();
Bounds title1Bounds =
title1.localToScene(title1.getLayoutBounds());
Bounds title2Bounds =
title2.localToScene(title2.getLayoutBounds());
if (tabPane.getSide().isHorizontal()) {
if (ltr) {
return Double.compare(
title1Bounds.getMinX(), title2Bounds.getMinX());
} else {
return Double.compare(
title2Bounds.getMaxX(), title1Bounds.getMaxX());
}
} else {
return Double.compare(
title1Bounds.getMinY(), title2Bounds.getMinY());
}
});
if (!tabPane.getTabs().equals(tabs)) {
Platform.runLater(() -> tabPane.getTabs().setAll(tabs));
}
});
StackPane root = new StackPane();
root.getChildren().add(tabPane);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("TabPane bug");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

How to execute multiple stage operations in a single frame with JavaFX?

I would like to execute multiple stage operations in one frame :
stage.sizeToScene()
stage.centerOnScreen()
Currently I can see that the stage is first resized, then centered. I would like both operations to be done atomically on the same re-paint.
Here is a working example :
package sample;
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.layout.HBox;
import javafx.stage.Stage;
public class Main extends Application {
private HBox first = new HBox();
private HBox second = new HBox();
private Button change1 = new Button("Go to 2nd");
private Button change2 = new Button("Go to 1st");
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Hello World");
first.setSpacing(10);
first.setAlignment(Pos.CENTER_LEFT);
first.getChildren().addAll(
change1, new Label("Hello"), new Label("World")
);
second.setSpacing(10);
second.setAlignment(Pos.CENTER_LEFT);
second.getChildren().addAll(
change2, new Label("BYE MY FRIENDS, THIS IS MUCH LONGER!")
);
change1.setOnAction(event -> {
primaryStage.getScene().setRoot(second);
primaryStage.sizeToScene();
primaryStage.centerOnScreen();
});
change2.setOnAction(event -> {
primaryStage.getScene().setRoot(first);
primaryStage.sizeToScene();
primaryStage.centerOnScreen();
});
primaryStage.setScene(new Scene(first));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
To reproduce, launch the application, move the window top-left and make it bigger. Then click on the button. You will see that the window is first resized, then moved at the center.
On this example case it's really really fast, because the application is really light. But with a real-world application it's much more noticable.

Using a FadeTransition on a Label causes the Label to appear different at start of transition

I need either a Label or a Text for my project. I need the label so that ellipsis can be used. The problem though, is when I try to use a FadeTransition, and play it, the label gets slightly darker at the start. Here is some demo code:
package com.neonorb.test;
import javafx.animation.FadeTransition;
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.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.IOException;
/**
* Created by chris on 7/20/15.
*/
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws IOException {
Label label = new Label("hello");
//Text label = new Text("hello);//Using Text instead of Label does not cause the weird behavior
FadeTransition fadeTransition = new FadeTransition(Duration.seconds(3), label);
fadeTransition.setFromValue(1.0);
fadeTransition.setToValue(0.0);
fadeTransition.setOnFinished(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
label.setOpacity(1.0);
}
});
Button button = new Button("play");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
fadeTransition.play();
}
});
BorderPane borderPane = new BorderPane();
borderPane.setCenter(label);
borderPane.setBottom(button);
primaryStage.setScene(new Scene(borderPane));
primaryStage.show();
}
}
So I either need a fix to this problem, or a way to use ellipsis in Text. Any ideas?
Set the opacity of the label to 0.99 initially:
label.setOpacity(0.99);
Also change the code inside setOnFinished method in the same way. Then, set the starting value of the fade transition to 0.99:
fadeTransition.setFromValue(0.99);
I know this is not the solution you are looking for, but this solution prevents the label from abruptly getting darker at the start. That is because the label actually starts with that darker status.

Auto scroll down a TextArea

I have a TextArea that doesn't scroll down when I add text in it. I thought using this answer, but my TextArea is connected to a StringProperty like this :
consoleTextArea.textProperty().bind(textRecu);
So the answer doesn't work for me, is there another way to make my TextArea scroll down every time I update it by the binding?
Here is fast demo of what i meant in comment about adding listener to the textRecu. Yep consoleTextArea.textProperty() can't be changed because of a binding. But textRecu has no binding => can be changed and we can add listener to it.
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private StringProperty textRecu = new SimpleStringProperty();
private TextArea consoleTextArea = new TextArea();
#Override
public void start(Stage primaryStage) throws Exception{
VBox root = new VBox();
Button button = new Button("Add some text");
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
//here you change textRecu and not consoleTextArea.textProperty()
textRecu.setValue(textRecu.getValue() +"New Line\n");
}
});
root.getChildren().addAll(consoleTextArea, button);
consoleTextArea.textProperty().bind(textRecu);
//here you also add listener to the textRecu
textRecu.addListener(new ChangeListener<Object>() {
#Override
public void changed(ObservableValue<?> observable, Object oldValue,
Object newValue) {
// from stackoverflow.com/a/30264399/1032167
// for some reason setScrollTop will not scroll properly
//consoleTextArea.setScrollTop(Double.MAX_VALUE);
consoleTextArea.selectPositionCaret(consoleTextArea.getLength());
consoleTextArea.deselect();
}
});
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Permanent text in a textfield in Java

I have a TextField in my program that will have data entered by the user, but I also have a variable value somewhere else that I need to permanently display at the end of my TextField. It cannot disappear when the user enters any data in the TextField. Can anyone give me a good implementation? Thanks.
[UserInput (miles)]
**Above is an example of what I am talking about. "Miles" needs to always be in the TextField while the UserInput is changing.
EDIT: "Implementation" was a bad choice of words. Let me rephrase, I can set up the field myself, but I am having trouble finding a way to set permanent text in a textfield. Just wondering if anyone knows an easy way.
You could put a transparent textfield over a label and bind the 2 together. Something like this but with better styling.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Text extends Application {
#Override
public void start(Stage primaryStage) {
TextField txtUser = new TextField();
txtUser.setStyle("-fx-background-color: transparent;-fx-border-color:blue;");
Label txtBG = new Label(" (miles)");
Label labelUser = new Label();
labelUser.textProperty().bind(txtUser.textProperty());
Label labelAll = new Label();
labelAll.textProperty().bind(Bindings.concat(
labelUser.textProperty())
.concat(txtBG.textProperty()));
StackPane sp = new StackPane();
sp.getChildren().addAll(txtBG, txtUser);
sp.setPrefSize(100, 12);
VBox root = new VBox();
root.getChildren().addAll(sp,labelUser,labelAll);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("transparent text test");
primaryStage.setScene(scene);
primaryStage.show();
}
}
I would use a HBox instead of a stack pane but it's one way to satisfy the requirement that "miles" is 'inside' the texfield's borders.
This is a small example doing what you want ! I have used the focus property of textfield to add and remove miles from it !
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextBinding extends Application {
#Override
public void start(Stage primaryStage) {
final TextField user = new TextField();
TextField demo = new TextField();
user.setStyle("-fx-background-color: transparent;-fx-border-color:blue;");
user.focusedProperty().addListener(new ChangeListener<Boolean>()
{
#Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
{
if (newPropertyValue)
{
user.setText(user.getText().replace(" miles", ""));
}
else
{
user.setText(user.getText().concat(" miles"));
}
}
});
VBox root = new VBox();
root.getChildren().addAll(user,demo);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("transparent text test");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String args[]) {
launch(args);
}
}

Categories

Resources