JavaFX - Style first and last tab only - javafx

Is there a way (CSS or Java) to style first and last tab only in a dynamic TabPane?
Example :
Thanks!

You can observe the ObservableList<Tab> returned by TabPane#getTabs() and update the style class of each Tab as appropriate. For example:
App.java:
import javafx.application.Application;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.css.Styleable;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TabPane.TabClosingPolicy;
import javafx.scene.control.TabPane.TabDragPolicy;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage primaryStage) {
TabPane pane = new TabPane();
pane.setTabClosingPolicy(TabClosingPolicy.ALL_TABS);
pane.setTabDragPolicy(TabDragPolicy.REORDER); // requires JavaFX 10+
pane.getTabs().addListener(App::tabsChanged);
pane.getTabs() // add tabs **after** adding ListChangeListener
.addAll(
new Tab("Test Tab #1", new StackPane(new Label("Content #1"))),
new Tab("Test Tab #2", new StackPane(new Label("Content #2"))),
new Tab("Test Tab #3", new StackPane(new Label("Content #3"))),
new Tab("Test Tab #4", new StackPane(new Label("Content #4"))),
new Tab("Test Tab #5", new StackPane(new Label("Content #5"))));
Scene scene = new Scene(pane, 600, 400);
scene.getStylesheets().add(getClass().getResource("/App.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
private static void tabsChanged(Change<? extends Tab> c) {
while (c.next()) {
if (c.wasRemoved()) {
for (Tab removed : c.getRemoved()) {
removed.getStyleClass().removeAll("first-tab", "last-tab");
}
}
}
ObservableList<? extends Tab> tabs = c.getList();
if (tabs.size() == 1) {
Tab tab = tabs.get(0);
addStyleClassIfAbsent(tab, "first-tab");
addStyleClassIfAbsent(tab, "last-tab");
} else if (!tabs.isEmpty()) {
Tab first = tabs.get(0);
addStyleClassIfAbsent(first, "first-tab");
first.getStyleClass().remove("last-tab");
Tab last = tabs.get(tabs.size() - 1);
addStyleClassIfAbsent(last, "last-tab");
last.getStyleClass().remove("first-tab");
for (Tab middle : tabs.subList(1, tabs.size() - 1)) {
middle.getStyleClass().removeAll("first-tab", "last-tab");
}
}
}
private static void addStyleClassIfAbsent(Styleable styleable, String styleClass) {
ObservableList<String> styleClasses = styleable.getStyleClass();
if (!styleClasses.contains(styleClass)) {
styleClasses.add(styleClass);
}
}
}
App.css:
.first-tab,
.last-tab {
-fx-base: pink;
}
The -fx-base is a looked-up color added by modena.css (i.e. the default user-agent stylesheet in JavaFX 8+). I set that instead of the -fx-background-color property in order to hook into the "theming" provided by modena.css. In the above example you can see the styles change dynamically by reordering the tabs via mouse-dragging (JavaFX 10+) or by closing tabs.
Note I would have preferred to use PseudoClass for this. However, from what I can tell, the Tab class does not allow you to (de)activate pseudo-classes directly. The way it handles the :selected pseudo-class is internal to the TabPane's default skin, meaning we can't access that same functionality reliably for our purposes from the outside.

Related

JavaFX - setStyle() changes not showing

I am creating a JavaFX application and I am having problems changing the background colors for certain components. For the buttons I am able to change their background radius, but not their background color. For the TableView I am unable to change the background color as well.
Here is my code and a picture of what I am seeing.
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableView;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class HomeUI extends Application {
private TableView transactionTable = new TableView();
private Button importButton = new Button("Import");
private Button trendButton = new Button("Trends");
private Button transactionButton = new Button("Transactions");
public static void main(String[] args){
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
// Set the text of defined fields
primaryStage.setTitle(" Budget Tracker");
// Import button information
// Create Anchor pane
AnchorPane anchorPane = new AnchorPane();
anchorPane.setPrefHeight(668.0);
anchorPane.setPrefWidth(1112.0);
anchorPane.setStyle("-fx-background-color: #545e75;");
// VBox to hold all buttons
VBox vBox = new VBox();
vBox.setPrefWidth(195);
vBox.setPrefHeight(668);
vBox.prefHeight(668);
vBox.prefWidth(203);
vBox.setStyle("-fx-background-color: #82a0bc;");
vBox.setLayoutX(0);
vBox.setLayoutY(0);
vBox.setAlignment(Pos.CENTER);
// importButton settings
importButton.setMnemonicParsing(false);
importButton.setPrefWidth(300);
importButton.setPrefHeight(80);
importButton.setStyle("-fx-background-color: #cacC9cc");
importButton.setStyle("-fx-background-radius: 0;");
// trendButton settings
trendButton.setPrefWidth(300);
trendButton.setPrefHeight(80);
trendButton.setStyle("-fx-background: #bcbdc1");
trendButton.setStyle("-fx-background-radius: 0");
// transactionButton settings
transactionButton.setPrefWidth(300);
transactionButton.setPrefHeight(80);
transactionButton.setStyle("-fx-base: #aeacb0");
transactionButton.setStyle("-fx-background-radius: 0");
// Add buttons to the vBox
vBox.getChildren().addAll(importButton, trendButton, transactionButton);
// TableView settings
transactionTable.setPrefHeight(568);
transactionTable.setPrefWidth(694);
transactionTable.setLayoutX(247);
transactionTable.setLayoutY(50);
transactionTable.setStyle("-fx-background-color: CAC9CC;");
transactionTable.setEditable(false);
// Add components to anchorPane
anchorPane.getChildren().addAll(vBox, transactionTable);
// Add anchorPane to scene and show it
primaryStage.setScene(new Scene(anchorPane));
primaryStage.show();
}
}
Buttons
By setting the style property, you replace the old style. Doing this multiple times does not combine the styles. You should set a value that combines the rules.
Instead of
transactionButton.setStyle("-fx-base: #aeacb0");
transactionButton.setStyle("-fx-background-radius: 0");
use
transactionButton.setStyle("-fx-base: #aeacb0; -fx-background-radius: 0;");
TableView
TableView shows little of it's own background. Most coloring you'll see is the background color of the TableRows that are added as descendants of the TableView. You'll need to use a CSS stylesheet to do this though (unless you want to use a rowFactory to do the styling).
.table-view .table-row-cell {
-fx-background-color: #CAC9CC;
}

Insert small icon (Emotion) in text message like Facebook chat message [duplicate]

I am trying to add an emoji to my chat program when my client types :)
I am trying to add this in the FXML controller. I have captured when the user types :) using the following code snippet :
if(chat.contains(":)")) {
...
}
My chat is printed into a textarea named taChat
taChat.appendText(chat + '\n');
Any help is appreciated!
A better approach would be to use TextFlow instead of using TextArea.
Advantages :
Individual Text are treated as children to the TextFlow. They can be added and accessed individually.
ImageView can be added directly to the TextFlow as a child.
A simple chat window with support for smiley :)
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class ChatWindowWithSmiley extends Application {
public void start(Stage primaryStage) {
TextFlow textFlow = new TextFlow();
textFlow.setPadding(new Insets(10));
textFlow.setLineSpacing(10);
TextField textField = new TextField();
Button button = new Button("Send");
button.setPrefWidth(70);
VBox container = new VBox();
container.getChildren().addAll(textFlow, new HBox(textField, button));
VBox.setVgrow(textFlow, Priority.ALWAYS);
// Textfield re-sizes according to VBox
textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty()));
// On Enter press
textField.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.ENTER) {
button.fire();
}
});
button.setOnAction(e -> {
Text text;
if(textFlow.getChildren().size()==0){
text = new Text(textField.getText());
} else {
// Add new line if not the first child
text = new Text("\n" + textField.getText());
}
if(textField.getText().contains(":)")) {
ImageView imageView = new ImageView("http://files.softicons.com/download/web-icons/network-and-security-icons-by-artistsvalley/png/16x16/Regular/Friend%20Smiley.png");
// Remove :) from text
text.setText(text.getText().replace(":)"," "));
textFlow.getChildren().addAll(text, imageView);
} else {
textFlow.getChildren().add(text);
}
textField.clear();
textField.requestFocus();
});
Scene scene = new Scene(container, 300, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output
For unicode Emoji support, please visit How to support Emojis

How can a dynamically generated JavaFX scene be changed in a single stage?

I'm currently working on a project requiring me to switch back and forward between scenes. I have already written some code for it but it isn't as elegant as I wanted to be, especially as there is few flickers when I switch between them and sometimes even the buttons that I have generated simply disappear only to appear once again when yet another scene has been generated. Moreover, the layout I'm using for my application isn't really fixed and I think that using FXML might be not suitable for what I'm doing.
Thank you.
This is what I'm using to change between scenes:
void changeScene(Stage stage,Scene scene){
stage.setScene(scene);
primaryStage.setFullScreen(true);
}
I assume by "switching between scenes" you mean that you want to change the entire content of the existing window.
There are two (very) slightly different ways you can do this. Either create a new Scene and pass it to the Stage's setScene(...) method. Or create the Parent that is the root of the new UI (either by FXML or otherwise), and pass it to the existing Scene's setRoot(...) method. There's no real advantage that I can see of one over the other.
Here's a minimal implementation of the second option. The UI is irrelevant to the question: the important parts are the event handlers for the "Login" button (which switches from the login scene to the main scene) and the "Logout" button (which switches back).
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class MinimalSceneSwitchingExample extends Application {
#Override
public void start(Stage primaryStage) {
LoginView loginView = new LoginView();
Scene scene = new Scene(loginView.getView(), 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class LoginView {
private final IntegerProperty loginAttempts ;
private final GridPane view ;
public LoginView() {
view = new GridPane();
TextField usernameTF = new TextField("user");
TextField passwordTF = new TextField("pass");
// Login button switches to main view:
Button loginButton = new Button("Login");
loginButton.setOnAction(event -> {
if (usernameTF.getText().equalsIgnoreCase("user")
&& passwordTF.getText().equalsIgnoreCase("pass")) {
// *** Switch to main view: ***
Parent mainView = new MainView().getView();
view.getScene().setRoot(mainView);
} else {
loginAttempts.set(loginAttempts.get()+1);
}
});
// just set up login UI... irrelevant to this example:
loginAttempts = new SimpleIntegerProperty();
usernameTF.setPromptText("Hint: user");
passwordTF.setPromptText("Hint: pass");
view.addRow(0, new Label("Username:"), usernameTF);
view.addRow(1, new Label("Password:"), passwordTF);
Label loginErrorMessage = new Label();
loginErrorMessage.textProperty().bind(
Bindings.when(loginAttempts.isEqualTo(0))
.then("")
.otherwise(Bindings.format("Login incorrect (Attempts: %d)",
loginAttempts)));
view.add(loginErrorMessage, 0, 2, 2, 1);
view.add(loginButton, 0, 3, 2, 1);
ColumnConstraints leftCol = new ColumnConstraints();
leftCol.setHgrow(Priority.NEVER);
leftCol.setHalignment(HPos.RIGHT);
ColumnConstraints rightCol = new ColumnConstraints();
rightCol.setHgrow(Priority.ALWAYS);
rightCol.setHalignment(HPos.LEFT);
view.getColumnConstraints().addAll(leftCol, rightCol);
GridPane.setHalignment(loginErrorMessage, HPos.CENTER);
GridPane.setHalignment(loginButton, HPos.CENTER);
view.setHgap(10);
view.setVgap(16);
view.setAlignment(Pos.CENTER);
}
public Parent getView() {
return view ;
}
}
public static class MainView {
private BorderPane view ;
public MainView() {
view = new BorderPane();
// *** logout button switches back to a login view: ***
Button logoutButton = new Button("Log out");
logoutButton.setOnAction(event ->
view.getScene().setRoot(new LoginView().getView()));
// Arbitrary UI, irrelevant to this example:
SplitPane splitPane = new SplitPane();
ListView<String> listView = new ListView<>();
IntStream.rangeClosed(1, 10)
.mapToObj(Integer::toString)
.map("Item "::concat)
.forEach(listView.getItems()::add);
Label bigLabel = new Label();
bigLabel.textProperty().bind(
listView.getSelectionModel().selectedItemProperty());
bigLabel.setFont(Font.font("Verdana", FontWeight.BOLD, 18));
BorderPane.setAlignment(bigLabel, Pos.CENTER);
BorderPane.setMargin(bigLabel, new Insets(10));
Label details = new Label();
details.textProperty().bind(
Bindings.when(
listView.getSelectionModel().selectedItemProperty().isNull())
.then("")
.otherwise(Bindings.format("This is where you would display "
+ "all sorts of details about %1$s. "
+ "If %1$s were really a model object, you "
+ "might have a GridPane displaying all its "
+ "properties, for example.",
listView.getSelectionModel().selectedItemProperty())));
details.setWrapText(true);
BorderPane detailsPane = new BorderPane(details, bigLabel, null, null, null);
splitPane.getItems().addAll(listView, detailsPane);
view.setCenter(splitPane);
view.setBottom(logoutButton);
BorderPane.setAlignment(logoutButton, Pos.CENTER);
BorderPane.setMargin(logoutButton, new Insets(8));
BorderPane.setMargin(splitPane, new Insets(16));
}
public Parent getView() {
return view ;
}
}
public static void main(String[] args) {
launch(args);
}
}

Capturing MouseEnter event in a Tab [Javafx]

I would like to be able to capture the MOUSEENTER event when hovering over a tab.
I have tried to do it from the Graphic of the tab, which is not the optimal solution, but it is a Node object with such events.
This is what I wrote:
tab.getGraphic().setOnMouseEntered((MouseEvent event) -> {
System.out.println("..... mouse entered");
//...
});
This solution does not error but is ignored by Javafx, any way to do this?
UPDATE: The way to create the tab and add its graphic, is like the following excerpt. The tab itself works fine and the graphic displays fine.
Tab tab = addChatTab(root, strName, strID, chat, false);
// setup tab graphic
switch (win.type) {
case wtChat:
if (chat !=null)
if (chat.isPublic()) {
tab.setGraphic(new ImageView(Main.me.imgTabPublic));
} else {
if (chat.isDCC())
tab.setGraphic(new ImageView(Main.me.imgTabDCC));
else tab.setGraphic(new ImageView(Main.me.imgTabPrivate));
}
break;
case wtWall:
tab.setGraphic(new ImageView(Main.me.imgTabWall));
break;
case wtMessage:
tab.setGraphic(new ImageView(Main.me.imgTabMessage));
break;
}
If you set a mouse handler on a graphic, then the handler will only be invoked when the mouse interacts with the graphic itself. In this example, the first tab has both text and a graphic set, so the mouse handler is not invoked when the mouse moves onto the text. The second tab sets no text but uses a label as the graphic, with the label containing the text. In that case the mouse handler is invoked when the mouse moves onto the text or image.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class TabPaneHoverTest extends Application {
#Override
public void start(Stage primaryStage) {
// hover only applies on graphic:
Tab tab1 = new Tab("Tab 1");
tab1.setGraphic(new Rectangle(16, 16, Color.RED));
// Tab only uses graphic (no text),
// so hover appears to apply to whole tab:
Tab tab2 = new Tab();
Label tab2Graphic = new Label("Tab 2", new Rectangle(16, 16, Color.GREEN));
tab2.setGraphic(tab2Graphic);
tab1.getGraphic().setOnMouseEntered(e -> System.out.println("Hover on tab 1"));
tab2.getGraphic().setOnMouseEntered(e -> System.out.println("Hover on tab 2"));
BorderPane root = new BorderPane(new TabPane(tab1, tab2));
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

TextArea loose focus when using scrollBar

When you create a TextArea, you can listen to its "focusedProperty".
But if the user touch the inner scrollBar of the TextArea (if it's too small), the focus of the TextArea is lost (since the scrollBar has the focus).
But as far as I am concerned, the TextArea is still having the focus because the scrollBar are part or the TextArea and there's even no way of accessing them.
How can I hack the textArea so that I would detect when the user is using the scrollBar? I want to hack/create a focusedProperty that will return true when the user is typing text or using the scrollBar.
Observe the Scene's focusOwner property, and create a BooleanBinding that is true if it is a descendant of the text area and false otherwise:
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextAreaFocusTest extends Application {
#Override
public void start(Stage primaryStage) {
TextArea textArea = new TextArea();
IntStream.rangeClosed(1, 200).forEach(i -> textArea.appendText(" "));
IntStream.rangeClosed(1, 80).forEach(i -> textArea.appendText("\nLine "+i));
Label label = new Label();
TextField textField = new TextField();
VBox root = new VBox(10, textArea, textField, label);
Scene scene = new Scene(root, 400, 400);
BooleanBinding focus = Bindings.createBooleanBinding(() -> {
for (Node n = scene.getFocusOwner(); n!= null ; n=n.getParent()) {
if (n == textArea) return true ;
}
return false ;
}, scene.focusOwnerProperty());
label.textProperty().bind(Bindings.when(focus).then("Focused").otherwise("Not Focused"));
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Here is a variation on #James_D's answer, in case you need to be able to obtain the focus binding from his answer without having a reference to the scene, e.g. if you need to set up the bindings before the text area is added to the scene, are implementing a library, or just want to have your code less entangled.
This solution uses the EasyBind library for convenient selection of nested property (selecting focusOwnerProperty from the sceneProperty).
public static Binding<Boolean> containsFocus(Node node) {
return EasyBind.monadic(node.sceneProperty())
.flatMap(Scene::focusOwnerProperty)
.map(owner -> {
for (Node n = owner; n != null; n = n.getParent()) {
if (n == node) return true ;
}
return false ;
})
.orElse(false); // when node.getScene() is null
}

Resources