The style is getting applied to font-size, boldstyle, italic style but not working for font-family.
Here is the syntax of the code.
public void setFontFamily() {
String family = (String) fontFamily.getValue();
textPreview.setText(family);
fontName = "-fx-font-family:" + (String) fontFamily.getValue() + ";";
previewText = "-fx-text:" + (String) fontFamily.getValue() + ";";
setFontPreviewProperties();
model.setFontValue(family);
}
private void setFontPreviewProperties() {
javafx.scene.text.Font selectedFont = javafx.scene.text.Font.font((String) fontFamily.getValue(), fontWeight,
fontPosture, size);
model.setFontFamily(selectedFont);
textPreview.setFont(selectedFont);
previewStyle = fontSize +fontName+ previewText+ boldStyle + italicStyle + underlineStyle;// fontName is not working here, everything else is working.
textPreview.setStyle(previewStyle);
}
Here is a sample app that could probably help you along the way.
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication127 extends Application
{
#Override
public void start(Stage primaryStage)
{
FontWeight fontWeight = FontWeight.BOLD;
FontPosture fontPosture = FontPosture.ITALIC;
double fontSize = 12;
TextField textField = new TextField();
TextArea textArea = new TextArea();
VBox vBox = new VBox(textField, textArea);
ListView<String> listView = new ListView();
List<String> familiesList = Font.getFamilies();
ObservableList<String> familiesObservableList = FXCollections.observableArrayList(familiesList);
listView.setItems(familiesObservableList);
listView.getSelectionModel().selectedItemProperty().addListener((Obs, oldFamily, newFamily) -> {
Font font = Font.font(newFamily, fontWeight, fontPosture, fontSize);//This is probably all you need.
textField.setText(newFamily);
textArea.setText(newFamily + System.lineSeparator() + System.lineSeparator() + "Pack my box with five dozen liquor jugs");
textArea.setFont(font);
});
HBox root = new HBox(listView, vBox);
Scene scene = new Scene(root, 700, 650);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
Related
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);
}
}
I´m trying to implement a very basic, simple and quiet typical dialog showing a list of checkboxes and a button for selecting all these checkboxes of the list.
The actual selection is working as expected. I also change the background color of the actual box showing the check symbol. But this color is only applied to the checkboxes visible without scrolling the list. When scrolling down the list you can see that all checkboxes are selected but the color is not set.
I´m using JDK10.
How can I force applying the color?
EDIT:
When first scrolling down and then clicking "select all" all colors of the previous checkboxes are also set correctly. But still not the following ones.
EDIT:
The same effect occurs when filtering the boxes using instanceof and change the colors by Region#setBackground(...).
package javafxcssbroken;
import java.util.StringJoiner;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFXCssBroken extends Application {
#Override
public void start(Stage primaryStage) {
ListView<CheckBox> listView = new ListView();
for (int i = 0; i < 100; i++) {
listView.getItems().add(new CheckBox("Element " + i));
}
Button markAll = new Button("Select all");
markAll.setOnAction(aevt -> {
Color newColor = Color.BLUE;
listView.getItems().stream()
.forEach(checkbox -> {
checkbox.setSelected(true);
checkbox.getChildrenUnmodifiable().stream()
.forEach(child -> child.setStyle(new StringJoiner(", ", "-fx-background-color: rgba(", ")")
.add(Double.toString(255 * newColor.getRed()))
.add(Double.toString(255 * newColor.getGreen()))
.add(Double.toString(255 * newColor.getBlue()))
.add(Double.toString(newColor.getOpacity()))
.toString()));
});
});
VBox vbox = new VBox(listView, markAll);
StackPane root = new StackPane();
root.getChildren().add(vbox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("JavaFXCssBroken");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
EDIT:
So a solution should be to introduce a class representing the data itself and also its associations discussed in the comments.
JavaFXCssBroken.java
package javafxcssbroken;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javax.swing.text.StyleConstants;
/**
* #param <I> The type of the items to display.
* #param <G> The type of the groups to associate items with.
*/
public class JavaFXCssBroken<I, G> extends Application {
private ListView<AssociatedItem<I, G>> listView;
private Set<I> items;
private Map<G, Color> groups;
private Optional<G> currentGroup;
public JavaFXCssBroken(Set<I> items, Map<G, Color> groups, Optional<G> initialGroup){
this.items = items;
this.groups = groups;
this.currentGroup = initialGroup;
}
#Override
public void start(Stage primaryStage) {
listView = new ListView();
listView.setCellFactory(lv -> {
ListCell<AssociatedItem<I, G>> cell = new ListCell<>();
cell.itemProperty().addListener((obs, oldVal, newVal) -> {
if(!cell.isEmpty() && newVal != null && newVal.getGroup().isPresent()){
cell.setBackground(new Background(
new BackgroundFill(groups.get(newVal.getGroup().get()), CornerRadii.EMPTY, Insets.EMPTY)));
}
});
cell.emptyProperty().addListener((obs, oldVal, newVal) -> {
if(newVal){
cell.setBackground(Background.EMPTY);
}
});
return cell;
});
items.stream().forEach(item -> listView.getItems().add(new AssociatedItem(item)));
Button markAll = new Button("Select all");
markAll.setOnAction(aevt -> {
listView.getItems().stream()
.forEach(item -> item.setGroup(currentGroup));
});
VBox vbox = new VBox(listView, markAll);
StackPane root = new StackPane();
root.getChildren().add(vbox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("JavaFXCssBroken");
primaryStage.setScene(scene);
primaryStage.show();
}
}
AssociatedItem.java
package javafxcssbroken;
import java.util.Optional;
public class AssociatedItem<I, G> {
private I item;
private Optional<G> group;
public AssociatedItem(I item) {
this.item = item;
group = Optional.empty();
}
public I getItem() {
return item;
}
public void setItem(I item) {
this.item = item;
}
public Optional<G> getGroup() {
return group;
}
public void setGroup(Optional<G> group) {
this.group = group;
}
#Override
public String toString() {
return item.toString();
}
}
Main.java
package javafxcssbroken;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javafx.application.Application;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Main extends Application{
#Override
public void start(Stage primaryStage) {
Map<Integer, Color> groups = Map.of(0, Color.RED, 1, Color.BLUE);
Set<String> items = new HashSet<>();
for (int i = 0; i < 100; i++) {
items.add("Elements " + i);
}
new JavaFXCssBroken(items, groups, Optional.of(0)).start(primaryStage);
}
public static void main(String[] args) {
launch(args);
}
}
At this point colors are set to all elements but the update of the colors is only applied when starting to scroll. Is it enough to introduce AssociatedItems as Observable?
Kleopatra is right. But assuming it is a simple example or training (even if you should take the good practice as soon as possible i.e even during the training), just use the css strength, create a stylesheet with this content :
StyleCheckbox.css
.check-box:selected > .box {
-fx-background-color:blue;
}
And modify your exisiting code by commenting the useless mechanic, and by adding the stylesheet you just create. :
markAll.setOnAction(aevt -> {
// Color newColor = Color.BLUE;
listView.getItems().stream().forEach(checkbox -> {
checkbox.setSelected(true);
// checkbox.getChildrenUnmodifiable().stream()
// .forEach(child -> child.setStyle(new StringJoiner(", ", "-fx-background-color:
// rgba(", ")")
// .add(Double.toString(255 * newColor.getRed()))
// .add(Double.toString(255 * newColor.getGreen()))
// .add(Double.toString(255 *
// newColor.getBlue())).add(Double.toString(newColor.getOpacity()))
// .toString()));
});
});
VBox vbox = new VBox(listView, markAll);
vbox.getStylesheets().add(this.getClass().getResource("StyleCheckbox.css").toExternalForm());
As kleopatra suggested overriding updateItem(...) and using an extractor works.
Main.java remains the same as in the last edit of the question.
AssociatedItem.java
package javafxcssbroken;
import java.util.Optional;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
public class AssociatedItem<I, G> {
private final ObjectProperty<I> item = new SimpleObjectProperty<>();
private final ObjectProperty<Optional<G>> group = new SimpleObjectProperty<>();
public AssociatedItem(I item) {
this.item.set(item);
group.set(Optional.empty());
}
public ObjectProperty<I> itemProperty() {
return item;
}
public I getItem() {
return itemProperty().get();
}
public void setItem(I item) {
this.item.set(item);
}
public ObjectProperty<Optional<G>> groupProperty() {
return group;
}
public Optional<G> getGroup() {
return groupProperty().get();
}
public void setGroup(Optional<G> group) {
this.group.set(group);
}
}
JavaFXCssBroken.java
package javafxcssbroken;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableObjectValue;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
* #param <I> The type of the items to display.
* #param <G> The type of the groups to associate items with.
*/
public class JavaFXCssBroken<I, G> extends Application {
private ListView<AssociatedItem<I, G>> listView;
private Set<I> items;
private ObservableValue<ObservableList<AssociatedItem<I, G>>> associatedItems
= new SimpleObjectProperty<>(
FXCollections.observableArrayList(i -> new Observable[]{i.itemProperty(), i.groupProperty()}));
private Map<G, Color> groups;
private Optional<G> currentGroup;
public JavaFXCssBroken(Set<I> items, Map<G, Color> groups, Optional<G> initialGroup) {
this.items = items;
this.groups = groups;
this.currentGroup = initialGroup;
}
#Override
public void start(Stage primaryStage) {
listView = new ListView();
listView.setCellFactory(lv -> new ListCell<AssociatedItem<I, G>>() {
#Override
protected void updateItem(AssociatedItem<I, G> item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setBackground(Background.EMPTY);
} else {
item.getGroup().ifPresent(group -> {
setBackground(new Background(
new BackgroundFill(groups.get(group), CornerRadii.EMPTY, Insets.EMPTY)));
});
setText(item.getItem().toString());
}
}
});
listView.itemsProperty().bind(associatedItems);
items.stream().forEach(item -> {
associatedItems.getValue().add(new AssociatedItem<>(item));
});
Button markAll = new Button("Select all");
markAll.setOnAction(aevt -> {
listView.getItems().stream()
.forEach(item -> item.setGroup(currentGroup));
});
VBox vbox = new VBox(listView, markAll);
StackPane root = new StackPane();
root.getChildren().add(vbox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("JavaFXCssBroken");
primaryStage.setScene(scene);
primaryStage.show();
}
}
package javafx;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ImageSlide extends Application {
// Width and height of image in pixels
private final double IMG_WIDTH = 600;
private final double IMG_HEIGHT = 300;
private final int NUM_OF_IMGS = 3;
private final int SLIDE_FREQ = 4; // in secs
#Override
public void start(Stage stage) throws Exception {
//root code
StackPane root = new StackPane();
Pane clipPane = new Pane();
// To center the slide show incase maximized
clipPane.setMaxSize(IMG_WIDTH, IMG_HEIGHT);
clipPane.setClip(new Rectangle(IMG_WIDTH, IMG_HEIGHT));
HBox imgContainer = new HBox();
//image view
ImageView imgGreen = new ImageView(new Image(getClass()
.getResourceAsStream("\\Merged1.pngg")));
ImageView imgBlue = new ImageView(new Image(getClass()
.getResourceAsStream("\\Merged2.png")));
ImageView imgRose = new ImageView(new Image(getClass()
.getResourceAsStream("\\Merged3.png")));
imgContainer.getChildren().addAll(imgGreen, imgBlue, imgRose);
clipPane.getChildren().add(imgContainer);
root.getChildren().add(clipPane);
Scene scene = new Scene(root, IMG_WIDTH, IMG_HEIGHT);
stage.setTitle("Image Slider");
stage.setScene(scene);
startAnimation(imgContainer);
stage.show();
}
//start animation
private void startAnimation(final HBox hbox) {
//error occured on (ActionEvent t) line
//slide action
EventHandler<ActionEvent> slideAction = (ActionEvent t) {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
//eventHandler
EventHandler<ActionEvent> resetAction = (ActionEvent t) {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1), hbox);
trans.setByX((NUM_OF_IMGS - 1) * IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
List<KeyFrame> keyFrames = new ArrayList<>();
for (int i = 1; i <= NUM_OF_IMGS; i++) {
if (i == NUM_OF_IMGS) {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), resetAction));
} else {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), slideAction));
}
}
//add timeLine
Timeline anim = new Timeline(keyFrames.toArray(new KeyFrame[NUM_OF_IMGS]));
anim.setCycleCount(Timeline.INDEFINITE);
anim.playFromStart();
}
//call main function
public static void main(String[] args) {
launch(args);
}
}
The lines
EventHandler<ActionEvent> slideAction = (ActionEvent t) {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
should be
EventHandler<ActionEvent> slideAction = (ActionEvent t) -> {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
Note the only addition ->. Which IDE are you using?
This is my sample code, In my project I have used scroll pane, but i am click outside of node and use arrow keys that nodes are move to Center,left,right,bottom.how to lock the node in same position,
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/**
*
* #author reegan
*/
public class ComboBoxEditable extends Application {
Node sub;
#Override
public void start(Stage primaryStage) {
ComboBox mainCombo = new ComboBox(listofCombo());
Button save = new Button("Save");
sub = new ComboBox(listofCombo());
HBox root = new HBox(20);
root.getChildren().addAll(mainCombo, sub,save);
ScrollPane pane = new ScrollPane(root);
mainCombo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if (newValue == "Others") {
sub = new TextField();
} else {
sub = new ComboBox(listofCombo());
}
root.getChildren().remove(1);
root.getChildren().add(1, sub);
}
});
save.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println(mainCombo.getValue());
if(sub.getClass() == ComboBox.class) {
ComboBox sub1 = (ComboBox)sub;
System.out.println(sub1.getValue());
} else {
TextField field = (TextField)sub;
System.out.println(field.getText());
}
}
});
Scene scene = new Scene(pane, 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);
}
public ObservableList listofCombo() {
ObservableList<String> list = FXCollections.observableArrayList();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf("Hello" + i));
}
list.add("Others");
return list;
}
}
I am ref this example code :JavaFX: scrolling vs. focus traversal with arrow keys
#James_D told "The default behavior for a scroll pane is that, if it has keyboard focus, the cursor (arrow) keys will cause it to scroll".So consume that event Ref for this solution JavaFX: scrolling vs. focus traversal with arrow keys
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package comboboxeditable;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/**
*
* #author reegan
*/
public class ComboBoxEditable extends Application {
Node sub;
#Override
public void start(Stage primaryStage) {
ComboBox mainCombo = new ComboBox(listofCombo());
Button save = new Button("Save");
sub = new ComboBox(listofCombo());
HBox root = new HBox(20);
root.getChildren().addAll(mainCombo, sub, save);
ScrollInterceptor pane = new ScrollInterceptor(root);
mainCombo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if (newValue == "Others") {
sub = new TextField();
} else {
sub = new ComboBox(listofCombo());
}
root.getChildren().remove(1);
root.getChildren().add(1, sub);
}
});
save.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println(mainCombo.getValue());
if (sub.getClass() == ComboBox.class) {
ComboBox sub1 = (ComboBox) sub;
System.out.println(sub1.getValue());
} else {
TextField field = (TextField) sub;
System.out.println(field.getText());
}
}
});
Scene scene = new Scene(pane, 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);
}
public ObservableList listofCombo() {
ObservableList<String> list = FXCollections.observableArrayList();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf("Hello" + i));
}
list.add("Others");
return list;
}
private static class ScrollInterceptor extends ScrollPane {
public ScrollInterceptor() {
remapArrowKeys(this);
}
public ScrollInterceptor(Node content) {
ScrollInterceptor.this.setContent(content);
remapArrowKeys(this);
}
private void remapArrowKeys(ScrollPane scrollPane) {
scrollPane.addEventFilter(KeyEvent.ANY, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP:
case DOWN:
case LEFT:
case RIGHT:
event.consume();
}
}
});
}
}
}
Can someone write a short JavaFX example of a Popover from ControlFX ? I haven't been able to get it to work. Any help is greatly appreciated!
This answer is a simple use of ControlsFX's PopOver.
When the mouse moves over the Label the PopOver appears. When the mouse exits the Label the PopOver disappears.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.controlsfx.control.PopOver;
/**
*
* #author Sedrick
*/
public class JavaFXApplication35 extends Application {
#Override
public void start(Stage primaryStage) {
//Build PopOver look and feel
Label lblName = new Label("John Doe");
Label lblStreet = new Label("123 Hello Street");
Label lblCityStateZip = new Label("MadeUpCity, XX 55555");
VBox vBox = new VBox(lblName, lblStreet, lblCityStateZip);
//Create PopOver and add look and feel
PopOver popOver = new PopOver(vBox);
Label label = new Label("Mouse mouse over me");
label.setOnMouseEntered(mouseEvent -> {
//Show PopOver when mouse enters label
popOver.show(label);
});
label.setOnMouseExited(mouseEvent -> {
//Hide PopOver when mouse exits label
popOver.hide();
});
StackPane root = new StackPane();
root.getChildren().add(label);
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);
}
}
you must google out for that
many sites are available nowadays
https://bitbucket.org/controlsfx/controlsfx/commits/dca9619e05de26d176aaafe785c3b94f022562ef
https://bitbucket.org/controlsfx/controlsfx/pull-request/158/initial-commit-of-popover-control/activity
and etc. just Google out.
Here we have program known as "HelloPopOver".
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.ListView;
import javafx.scene.control.Slider;
import javafx.scene.control.TitledPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import org.controlsfx.ControlsFXSample;
import org.controlsfx.control.popover.PopOver;
import org.controlsfx.control.popover.PopOverController;
import org.controlsfx.control.popover.PopOverHeader;
import org.controlsfx.control.popover.PopOverTitledPane;
import org.controlsfx.samples.Utils;
public class HelloPopOver extends ControlsFXSample {
private PopOverController<PopOver, Button> controller = new MyController();
#Override
public Node getPanel(Stage stage) {
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setAlignment(Pos.CENTER);
grid.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent evt) {
controller.hidePopOver();
}
});
for (int i = 0; i < 10; i++) {
final Button button = new Button("Button " + i);
grid.add(button, i % 2, i / 2);
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent evt) {
controller.hidePopOver();
if (evt.getClickCount() == 2) {
controller.setupPopOver(button);
controller.showPopOver(button, evt.getScreenX(),
evt.getScreenY());
}
}
});
}
return grid;
}
class MyController extends PopOverController<PopOver, Button> {
#Override
protected PopOver createPopOver(final Button button) {
PopOver editor = new PopOver();
PopOverHeader<?> header = (PopOverHeader<?>) editor.getHeader();
header.setTitle(button.getText() + " (edit me)");
header.setSubtitle("Just some random controls (edit me)");
editor.setDetachedTitle(button.getText());
editor.getPanes().add(createTitledPane("Start Time & Duration"));
editor.getPanes().add(createTitledPane("Dependencies"));
editor.getPanes().add(createTitledPane("Priority"));
editor.getPanes().add(createTitledPane("Assignments / Resources"));
editor.setExpandedPane(editor.getPanes().get(0));
editor.setFooter(new Footer());
ColorPicker picker = (ColorPicker) header.getExtra();
picker.valueProperty().addListener(new ChangeListener<Color>() {
#Override
public void changed(ObservableValue<? extends Color> value,
Color oldColor, Color newColor) {
button.setBackground(new Background(new BackgroundFill(
newColor, CornerRadii.EMPTY, Insets.EMPTY)));
}
});
return editor;
}
}
private TitledPane createTitledPane(String title) {
VBox box = new VBox(5);
box.getChildren().add(new Button("Test"));
box.getChildren().add(new Slider());
ListView<String> view = new ListView<>();
view.setPrefHeight(100);
box.getChildren().add(view);
final TitledPane pane = new PopOverTitledPane(title, box);
pane.setTextAlignment(TextAlignment.LEFT);
Pane connectivityArrow = (Pane) pane.lookup(".arrow");
if (connectivityArrow != null) {
connectivityArrow.translateXProperty().bind(
pane.widthProperty().subtract(
connectivityArrow.widthProperty().multiply(2)));
}
return pane;
}
class Footer extends FlowPane {
public Footer() {
super(Orientation.HORIZONTAL);
setAlignment(Pos.CENTER_RIGHT);
Button delete = new Button("Delete");
getChildren().add(delete);
delete.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent evt) {
}
});
}
}
public static void main(String[] args) {
Application.launch(args);
}
#Override
public String getSampleName() {
return "PopOver";
}
#Override
public String getJavaDocURL() {
return Utils.JAVADOC_BASE
+ "org/controlsfx/control/popover/PopOver.html";
}
#Override
public String getSampleDescription() {
return "An implementation of a pop over control as used by Apple for its iCal application. A pop over allows"
+ "the user to see and edit an objects properties. The pop over gets displayed in its own popup window and"
+ "can be torn off in order to create several instances of it.";
}
}