How to delete branching TreeItems from a TreeView in javafx? - recursion

How would I implement the method
private void wipeTreeViewStructure(TreeItem node)
where "node" is a TreeItem which, along with all of its connected TreeItems, gets erased on execution? I tried something along the lines of
private void wipeTreeViewStructure(TreeItem node) {
for (TreeItem i : node.getChildren()) {
wipeTreeViewStructure(i);
i.delete();
}
}
but that has two major flaws:
I'm getting an "Incompatible types" error in the "i", which I don't know what to make out of.
there is apparently no delete() or any similar method implemented for TreeItem.
With this many unknowns, I thought it would be better to just ask how it's done.

Your incompatible types error is (I think) because you are using raw types, instead of properly specifying the type of the object in the TreeItem. In other words, you should be using
TreeItem<Something>
instead of just the raw
TreeItem
The Something is whatever you are using as data in your tree. Your IDE should be giving you lots of warnings over this.
You don't need recursion at all here. To remove the tree item, just remove it from its parent's list of child nodes. It will effectively take all its descendents with it. You can do
node.getParent().getChildren().remove(node);
and that should do everything you need. (If the node might be the root of the tree, then you should check for that first.)
SSCCE:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class TreeViewWithDelete extends Application {
#Override
public void start(Stage primaryStage) {
TreeItem<String> treeRoot = new TreeItem<>("Root");
treeRoot.setExpanded(true);
TreeView<String> tree = new TreeView<>(treeRoot);
tree.getSelectionModel().select(treeRoot);
Button delete = new Button("Delete");
delete.setOnAction(e -> {
TreeItem<String> selected = tree.getSelectionModel().getSelectedItem();
selected.getParent().getChildren().remove(selected);
});
delete.disableProperty().bind(tree.getSelectionModel().selectedItemProperty().isNull()
.or(tree.getSelectionModel().selectedItemProperty().isEqualTo(treeRoot)));
TextField textField = new TextField();
Button add = new Button("Add");
EventHandler<ActionEvent> addAction = e -> {
TreeItem<String> selected = tree.getSelectionModel().getSelectedItem();
if (selected == null) {
selected = treeRoot ;
}
String text = textField.getText();
if (text.isEmpty()) {
text = "New Item";
}
TreeItem<String> newItem = new TreeItem<>(text);
selected.getChildren().add(newItem);
newItem.setExpanded(true);
tree.getSelectionModel().select(newItem);
};
textField.setOnAction(addAction);
add.setOnAction(addAction);
HBox controls = new HBox(5, textField, add, delete);
controls.setAlignment(Pos.CENTER);
controls.setPadding(new Insets(5));
BorderPane root = new BorderPane(tree, null, null, controls, null);
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Related

how to edit/change name in output in javafx

here is my code
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class Main extends Application
{
private BorderPane root;
TreeView<String> tree;
#Override
public void start(Stage primaryStage) throws Exception
{
root = new BorderPane();
root.setLeft(getLeftHBox());
Scene scene = new Scene(root, 900, 500);
primaryStage.setTitle("JavaFx");
primaryStage.setScene(scene);
primaryStage.show();
}
private HBox getLeftHBox()
{
HBox hbox = new HBox();
Text text= new Text("Fall tree");
text.setFont(Font.font("Helvetica", FontWeight.BOLD,16));
VBox vbox =new VBox(10);
vbox.setPadding(new Insets(10));
TreeItem<String> Library,module,unite,translateA ,translateB,rotate;
//Root
Library = new TreeItem<>();
Library.setExpanded(true);
//module-Child of Root
module = makeBranch("module",Library);
makeBranch("Parameter X",module);
makeBranch("Parameter y",module);
//Unite-Child of module
unite = makeBranch("unite",module);
makeBranch("Parameter uX",unite);
makeBranch("Parameter uy",unite);
//TranslateA-Child of Unite
translateA = makeBranch("translateA",unite);
makeBranch("Parameter taX",translateA);
makeBranch("Parameter tay",translateA);
//TranslateB-Sibling of TranslateA
translateB = makeBranch("translateB",unite);
makeBranch("Parameter tbX",translateB);
makeBranch("Parameter tby",translateB);
//Rotate-Child of TranslateB
rotate = makeBranch("rotate",translateB);
makeBranch("Parameter RX",rotate);
makeBranch("Parameter RY",rotate);
tree= new TreeView<>(Library);
tree.setShowRoot(false);
vbox.getChildren().addAll(text,tree);
hbox.getChildren().addAll(vbox);
return hbox;
}
private TreeItem<String> makeBranch(String title, TreeItem<String> parent) {
TreeItem<String>item = new TreeItem<>(title);
item.setExpanded(true);
parent.getChildren().add(item);
return item;
}
public static void main(String[] args)
{
Application.launch(args);
}
}
in the output i got the fall tree/drop down menu. my question is how to edit the names in output. how can i give new titles/names to branches in output and that appear in my code.
Example: when you execute program, i have a branch name "module" on top of output. i want to change that name and write "Rotate_Module" in output.
(i can simply change the code to do that but i want to change it in output and that should automatically appear in my code)
Note# i want to change every name. thank you
To make the tree editable, which is what I think you mean in this question, you need to specify that you want the tree to use cells which incorporate a text field. You can do this with:
tree.setEditable(true);
tree.setCellFactory(TextFieldTreeCell.forTreeView());
If the user edits the tree and makes changes, then those changes will be stored in the TreeItem's valueProperty(); i.e. you can retrieve the values with module.getValue(), etc.
So to make the user's changes persistent, you will need to retrieve all those values and save them to a file (or database, or some other kind of persistent storage) when the application closes. To use those values, when you start the application, read the values from the file (or database, etc) and use those values when you create the tree items.

Add text under buttons in Dialog

I was wondering if there is a way to display some text (like a info) under the buttons of a Dialog ? I've looked in many places, but even to align the buttons seems messy (from this post).
This is what I got for now. I just want the "Set my choice ..." text under the 2 buttons.
I looked for a function in the documentation that could help me display the way I want (like "getButtonBar()" or something like that) with no chance. Also creating a new ButtonBar seems a bit complicated for what I want to achieve.
I also tried to create a stage that could look like a dialog, but I needed the result incoming from clicking "Yes / No" in the same way the Dialogs do.
Is there any way to achieve want I want ? Or do I have to build it completely myself ? Thanks !
Just override the createButtonBar() method of DialogPane:
DialogPane pane = new DialogPane() {
#Override
public Node createButtonBar() {
VBox vbox = new VBox(5);
vbox.setAlignment(Pos.BOTTOM_RIGHT);
vbox.setPadding(new Insets(5));
vbox.getChildren().add(super.createButtonBar());
vbox.getChildren().add(new Label("Additional text"));
return vbox ;
}
};
Here's a SSCCE:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CustomDialogPaneTest extends Application {
#Override
public void start(Stage primaryStage) {
Button button = new Button("Show Dialog");
button.setOnAction(e -> {
DialogPane pane = new DialogPane() {
#Override
public Node createButtonBar() {
VBox vbox = new VBox(5);
vbox.setAlignment(Pos.BOTTOM_RIGHT);
vbox.setPadding(new Insets(5));
vbox.getChildren().add(super.createButtonBar());
vbox.getChildren().add(new Label("Additional text"));
return vbox ;
}
};
CheckBox checkBox = new CheckBox("A check box");
pane.setContent(checkBox);
pane.setHeaderText("The header");
pane.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setDialogPane(pane);
dialog.showAndWait().ifPresent(System.out::println);
});
StackPane root = new StackPane(button);
root.setPadding(new Insets(20));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Adding value from textfield

I a m creating a java application and I have a problem.
Here is the code.
package javastackoverflow;
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.FlowPane;
import javafx.stage.Stage;
public class Javastackoverflow extends Application {
TextField deduct2;
Label text;
double ammount = 0.0;
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Apply");
text = new Label(Double.toString(ammount));
btn.setOnAction((e->{
double getamount = Double.parseDouble(deduct2.getText());
text.setText(Double.toString(getamount)+ ammount);
//this is where the program is suppose to get the amount and add it to amount, notice the + sign.
}))
;
deduct2 = new TextField();
FlowPane root = new FlowPane();
root.setAlignment(Pos.CENTER);
root.getChildren().addAll(btn,deduct2,text);
Scene scene = new Scene(root, 400, 450);
primaryStage.setTitle("Yo Stack");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
What it is suppose to do
When the user enters a number into the textfield the program is suppose to
to take that number and add it to ammount = 0;
My problem
But when ever the using enters a new number the text changes to That number. Remember I would like it to add to the currant number like (currant number = 23; user enters new Number) new number = 3; I would like results to equal = 26 but right now the program shows the result 3;
What I think
I think the problem is in the onAction() method.
I think that the text.setText() method is displaying the currant text entered into the textfield, rather then adding it to ammount.
I alse don't think I am using the correct operator from this line of code. That may be part of the problem.
text.setText(Double.toString(getamount)+ ammount);
notice how I use the + sign, that + adds the getamount to ammount..or its supposed to. But when I change that plus sign to - or * I get this error
===============================
bad operand types for binary operator '*'
first type: String
second type: TextField
===============================
As you can probably tell I really would like this code to be correct so if you don't understand something please comment before you report me. Then I can change it fast. Thank you!
You are adding the amount to the getAmount variable when amount = 0.0
Try adding the new value to getAmount
package javastackoverflow;
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.FlowPane;
import javafx.stage.Stage;
public class Javastackoverflow extends Application {
TextField deduct2;
Label text;
double getamount = 0.0; //Edit 1
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Apply");
text = new Label(Double.toString(ammount));
btn.setOnAction((e->{
getamount += Double.parseDouble(deduct2.getText()); //Edit 2
text.setText(Double.toString(getamount));
//this is where the program is suppose to get the amount and add it to amount, notice the + sign.
}))
;
deduct2 = new TextField();
FlowPane root = new FlowPane();
root.setAlignment(Pos.CENTER);
root.getChildren().addAll(btn,deduct2,text);
Scene scene = new Scene(root, 400, 450);
primaryStage.setTitle("Yo Stack");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

javafx 8 listview first and last row

Is there a way to determine the first and last visible row of a listview? In other words I'm looking for two indexes into an array that populates a listview which represent the top and the bottom row of the 'display window'.
You could get the VirtualFlow of the ListView which has methods for getting the first and last rows.
Example:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.scene.Scene;
import javafx.scene.control.IndexedCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import com.sun.javafx.scene.control.skin.VirtualFlow;
public class ListViewSample extends Application {
#Override
public void start(Stage stage) {
VBox box = new VBox();
ListView<Integer> list = new ListView<>();
ObservableList<Integer> items = FXCollections.observableArrayList();
for( int i=0; i < 100; i++) {
items.add(i);
}
list.setItems(items);
box.getChildren().add(list);
VBox.setVgrow(list, Priority.ALWAYS);
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.show();
VirtualFlow flow = (VirtualFlow) list.lookup( ".virtual-flow");
flow.addEventFilter(Event.ANY, event -> {
IndexedCell first = flow.getFirstVisibleCellWithinViewPort();
IndexedCell last = flow.getLastVisibleCellWithinViewPort();
System.out.println( list.getItems().get( first.getIndex()) + " - " + list.getItems().get( last.getIndex()) );
});
}
public static void main(String[] args) {
launch(args);
}
}
You see the fully visible first and last items in the console.
ps: I leave the no data check and event handling to you
Alternate version without css lookup:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.IndexedCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import com.sun.javafx.scene.control.skin.VirtualFlow;
public class ListViewSample extends Application {
ListView<String> list = new ListView<String>();
#Override
public void start(Stage stage) {
VBox box = new VBox();
ListView<Integer> list = new ListView<>();
ObservableList<Integer> items = FXCollections.observableArrayList();
for( int i=0; i < 100; i++) {
items.add(i);
}
list.setItems(items);
box.getChildren().add(list);
VBox.setVgrow(list, Priority.ALWAYS);
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.show();
VirtualFlow virtualFlow = null;
for( Node node: list.getChildrenUnmodifiable()) {
if( node instanceof VirtualFlow) {
virtualFlow = (VirtualFlow) node;
}
}
final VirtualFlow flow = virtualFlow;
flow.addEventFilter(Event.ANY, event -> {
IndexedCell first = flow.getFirstVisibleCellWithinViewPort();
IndexedCell last = flow.getLastVisibleCellWithinViewPort();
System.out.println( list.getItems().get( first.getIndex()) + " - " + list.getItems().get( last.getIndex()) );
});
}
public static void main(String[] args) {
launch(args);
}
}
UPDATE
VirtualFlow is available only after the ListView has been rendered, because it uses Layout parameters which are not available until after the ListView is visible on the stage. So I had to make sure that I got the VirtualFlow when it was certain that the ListView had been rendered. Since I was manipulating the list with various methods I call this method at the end of each method:
private VirtualFlow flow;
private void updateListView(int centreIndex) {
if (flow == null)
flow = (VirtualFlow) myListView.lookup(".virtual-flow");
if (flow != null){
IndexedCell first = flow.getFirstVisibleCellWithinViewPort();
IndexedCell last = flow.getLastVisibleCellWithinViewPort();
System.out.println(first.getIndex() + " - " + last.getIndex());
}
// Now the list can be selectively 'redrawn' using the scollTo() method,
// and using the .getSelectionModel().select(centreIndex) to set the
// desired cell
}
It's bit of a hack, but it works. Using layout parameters does have a drawback though that needs to be considered. If the height of the ListView is only 1 pixel less than the total height of all rows, n number of rows will be visible, but the flow will report n-1 rows which will appear to be a discrepancy at first. Hence keeping a fixed layout height is imperative. At least now by using scrollTo(..) I have control over the position of the selected item in the list (I want to keep it centred in the list display when an item is dragged through the list). This solution leaves me feeling uneasy, but it seems to be the only 'simple' way.
Just a note on the odd-looking logic. It seems that getting the flow takes time, while the program keeps executing. The second (flow != null) is necessary to avoid a NullPointerException.
UPDATE 2
My hack turns out not to work. The whole hack is dependent on timing. Rendering is done on a different thread and as soon as I changed the order of instantiation of classes in my app, I got a NullPointerException again. I turned to the Java doc:
"JavaFX is not thread safe and all JavaFX manipulation should be run on the JavaFX processing thread. If you allow a JavaFX application to interact with a thread other than the main processing thread, unpredictable errors will occur"
And they do! So forget the above - it does not work and will make you scratch your head (and more!) trying to debug it ;-)

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);
}
}

Resources