imageview in tableview. JavaFX. Cant explain what is this? - imageview

This is code mainController for my fxml form. Image in tableview work, but some strangeable.
Add first row - ok.
Add second: watch image in second from the start and first from the end.
Add third: watching in third row from the start and fourth from the end... etc..
What is this? data no add in those rows, but image adding. Where is problem?
package cardiler;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import viewpages.AddFilterWindowController;
public class MainWindowController {
#FXML
private ResourceBundle resources;
#FXML
private URL location;
// Фильтры ------------------------------------------------ //
#FXML
private TableView<CarFilters> filtersTable;
#FXML
private TableColumn<CarFilters, String> firmColumn;
#FXML
private TableColumn<CarFilters, String> modelColumn;
private ObservableList<CarFilters> filtersData = FXCollections.observableArrayList();
// Результаты поиска -------------------------------------- //
#FXML
private TableView<CarResult> scanResultsTable;
#FXML
private TableColumn<CarResult, String> firmRTColumn;
#FXML
private TableColumn<CarResult, String> modelRTColumn;
#FXML
private TableColumn<CarResult, CarPhoto> photoRTColumn;
private ObservableList<CarResult> resultsData = FXCollections.observableArrayList();
#FXML
void handleAddFilterButton(ActionEvent event) {
try {
// Load the fxml file and create a new stage for the popup
FXMLLoader loader = new FXMLLoader(CarDiler.class.getResource("/viewpages/AddFilterWindow.fxml"));
AnchorPane page = (AnchorPane) loader.load();
Stage dialogStage = new Stage();
dialogStage.setTitle("Edit Person");
dialogStage.initModality(Modality.WINDOW_MODAL);
// dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
// Set the person into the controller
AddFilterWindowController controller = loader.getController();
controller.setDialogStage(dialogStage);
CarFilters carFilter = new CarFilters();
controller.setCarFilterLink(carFilter);
// Show the dialog and wait until the user closes it
dialogStage.showAndWait();
if (controller.isOkClicked())
{
filtersData.add(carFilter);
}
// return controller.isOkClicked();
} catch (IOException e) {
// Exception gets thrown if the fxml file could not be loaded
e.printStackTrace();
// return false;
}
}
#FXML
void handleSearchBuyers(ActionEvent event) {
}
#FXML
void handleSearchSellers(ActionEvent event) {
}
#FXML
void handleStartButton(MouseEvent event) {
resultsData.add(new CarResult("ddd", "sss", new CarPhoto("ss", "dd", "/resources/images/start_button.png")));
scanResultsTable.setItems(resultsData);
}
#FXML
void initialize() {
// Результат --------------------------------------------------------------------- //
assert scanResultsTable != null : "fx:id=\"scanResultsTable\" was not injected: check your FXML file 'MainWindow.fxml'.";
firmRTColumn.setCellValueFactory(new PropertyValueFactory<CarResult, String>("firm"));
modelRTColumn.setCellValueFactory(new PropertyValueFactory<CarResult, String>("model"));
photoRTColumn.setCellValueFactory(new PropertyValueFactory<CarResult, CarPhoto>("photo"));
// SETTING THE CELL FACTORY FOR THE ALBUM ART
photoRTColumn.setCellFactory(new Callback<TableColumn<CarResult,CarPhoto>,
TableCell<CarResult,CarPhoto>>(){
#Override
public TableCell<CarResult, CarPhoto> call(TableColumn<CarResult, CarPhoto> param) {
return new TableCell<CarResult, CarPhoto>(){
ImageView imageview;
{
imageview = new ImageView();
imageview.setFitHeight(20);
imageview.setFitWidth(20);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(imageview);
}
#Override
public void updateItem(CarPhoto item, boolean empty) {
super.updateItem(item, empty);
if(!empty && !item.equals(null)){
imageview.setImage(new Image(item.getPhoto()));
}
System.out.println(item);
}
};
}
});
scanResultsTable.setItems(resultsData);
// Филтры ------------------------------------------------------------------------ //
assert filtersTable != null : "fx:id=\"filtersTable\" was not injected: check your FXML file 'MainWindow.fxml'.";
// Маппинг колонок с полями класса потомка
firmColumn.setCellValueFactory(new PropertyValueFactory<CarFilters, String>("firm"));
modelColumn.setCellValueFactory(new PropertyValueFactory<CarFilters, String>("model"));
filtersTable.setItems(filtersData);
}
}

The tableview and listview cells are reused to render different row data of the source list. Your problem probably lays on the updating of the cell item. Try this:
#Override
public void updateItem(CarPhoto item, boolean empty) {
super.updateItem(item, empty);
if (!empty && !item.equals(null)) {
imageview.setImage(new Image(item.getPhoto()));
}
else {
imageview.setImage(null);
}
System.out.println(item);
}

Related

JavaFx: Check if Username and Password in Registration is matched with Login

I want to check if usernames and passwords in Regisration.java are matched with usernames and passwords in Login.java. For example, if I type in "Ali" as username, and "123" as password in Registration.java and saved it, which I have already done. Then, when I go to Login.java and type in for example "Ross" as username and "1010" as password in Login.java, it will print "Username or Password is wrong"
Users.java:
import java.util.ArrayList;
/**
*
* #author ammar
*/
public class Users {
public static ArrayList<String> usernames = new ArrayList<String>();
public static ArrayList<String> passwords = new ArrayList<String>();
public void addusers(String u, String p){
usernames.add(u);
passwords.add(p);
}
public ArrayList getUserNames()
{
return usernames;
}
public ArrayList getPasswords()
{
return passwords;
}
}
Login.java
package javaapplication6;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* #author ammar
*/
public class LoginController implements Initializable {
#FXML
private Label Titlelbl;
#FXML
private Label UserNamelbl;
#FXML
private Label Passwordlbl;
#FXML
private Button Registerbtn;
#FXML
private Button Loginbtn;
#FXML
private Label Forgetbtn;
private Label Outputlbl;
#FXML
private TextField UserNametxt;
#FXML
private TextField Passwordtxt;
#FXML
private Label Outputlbl1;
#FXML
private Label Outputlbl2;
#FXML
private ImageView Img;
#FXML
private Button Viewbtn;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Image image = new Image(getClass().getResourceAsStream("/javaapplication6/icons/uqu.png"));
Img.setImage(image);
}
#FXML
private void Login(ActionEvent event) {
var valid = true;
// Validate the username field
if (UserNametxt.getText().isEmpty() ) {
valid = false;
Outputlbl1.setText("Please Enter User Name ");
} else if (UserNametxt.getText().equals("Ali")) {
Outputlbl1.setText("Welcome");
} else {
Outputlbl1.setText("In");
}
if (Passwordtxt.getText().isEmpty()) {
valid = false;
Outputlbl2.setText("Please Enter Password");
} else {
Outputlbl2.setText("");
}
}
#FXML
private void Registerbtn(ActionEvent event) {
try {
((Node)event.getSource()).getScene().getWindow().hide();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("SecondWindow.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root1));
stage.show();
} catch (Exception e) {
System.out.println("Cant load new window");
}
}
#FXML
private void view(ActionEvent event) {
Users u = new Users();
ArrayList<String> uname = new ArrayList<String>();
ArrayList<String> pass = new ArrayList<String>();
uname = u.getUserNames();
pass = u.getPasswords();
System.out.println("The user Names-"+uname);
}
}
Registration.java (I named it SecondWindowController.java):
package javaapplication6;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* #author ammar
*/
public class SecondWindowController implements Initializable {
#FXML
private Button Backbtn;
#FXML
private Button Savebtn;
#FXML
private TextField UserNameReg;
#FXML
private TextField PasswordReg;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void back(ActionEvent event) throws IOException {
((Node)event.getSource()).getScene().getWindow().hide();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Login.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root1));
stage.show();
}
#FXML
private void save(ActionEvent event) {
Users user = new Users();
user.addusers(UserNameReg.getText(), PasswordReg.getText());
}
}
FXMain:
package javaapplication6;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* #author ammar
*/
public class FXMain extends Application {
#Override
public void start(Stage stage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/javaapplication6/Login.fxml"));
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.setTitle("UQU");
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

JavaFX custom TreeView with ComboBox

I try to create a TreeView that will have on every branch and leaf a ComboBox, an "add child" Button and an "remove child" Button.
Here is my code
package example;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author me
*/
public class Example extends Application {
String[] companyNames = new String[10];
#Override
public void start(Stage primaryStage) {
companyNames[0]="FORD";
companyNames[1]="MG";
companyNames[2]="LADA";
companyNames[3]="BMW";
companyNames[4]="KIA";
companyNames[5]="HYUNDAI";
companyNames[6]="AUDI";
companyNames[7]="MERCEDES";
companyNames[8]="DACIA";
companyNames[9]="TOYOTA";
final TreeItem<String> treeRootItem = new TreeItem<>("Root");
final TreeView<String> treeView = new TreeView<>(treeRootItem);
treeRootItem.setExpanded(true);
treeView.setCellFactory(e -> new CustomCell());
VBox mainVBox = new VBox();
mainVBox.getChildren().add(treeView);
Scene scene1 = new Scene(mainVBox,1600,600);
primaryStage.setScene(scene1);
primaryStage.show();
primaryStage.centerOnScreen();
}
//function custom TreeCell CustomCell
class CustomCell extends TreeCell<String> {
#Override
protected void updateItem(String item, boolean empty)
{
ComboBox companiesComboBox = new ComboBox();
Button addChildButton = new Button("Add Child");
Button removeButton = new Button("Remove Child");
super.updateItem(item, empty);
if (isEmpty()) {
setGraphic(null);
setText(null);
}
else {
HBox cellBox = new HBox(10);
if (item.equals("Root"))
{
cellBox.getChildren().addAll(companiesComboBox,addChildButton);
}
else cellBox.getChildren().addAll(companiesComboBox,addChildButton,removeButton);
setGraphic(cellBox);
setText(null);
}
companiesComboBox.getItems().addAll((Object[]) companyNames);
addChildButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
String selection=companiesComboBox.getSelectionModel().getSelectedItem().toString();
TreeItem<String> childNode1 = new TreeItem<>("Child Node");
getTreeItem().getChildren().add(childNode1);
}});
removeButton.setOnAction(value -> {
//somehow i will remove the leaf/branch
});
}
}
public static void main(String[] args) {
launch(args);
}
}
(As Alexandra pointed out, in my prior post, i had many Java Naming Conventions wrong, i hope i fixed it now.
A am sorry that i deleted my prior post but it was off topic with many wrongs so i decided to make a small research how to make a post with better code and more specific without mistakes and come back a few days later.I hope that now is presentable.)
The problem that i have is that when i add a new child , the hole tree loses the ComboBox selection.
Here is a picture of the project running https://ibb.co/8MVDqhX
Any help/suggestion will be appreciated
UPDATE:
After Slaw answer i tried to create a Model Class named SelectedCompanyClass
package example;
import javafx.beans.property.StringProperty;
/**
*
* #author me
*/
public class SelectedCompanyClass {
public String companyNameString;
public SelectedCompanyClass(String companyNameString) {
this.companyNameString = companyNameString;
}
}
And i changed my main class like this
package example;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author me
*/
public class Example extends Application {
String[] companyNames = new String[10];
int x=0;
SelectedCompanyClass SelectedCompanyClass1;
#Override
public void start(Stage primaryStage) {
this.SelectedCompanyClass1 = new SelectedCompanyClass("root");
companyNames[0]="FORD";
companyNames[1]="MG";
companyNames[2]="LADA";
companyNames[3]="BMW";
companyNames[4]="KIA";
companyNames[5]="HYUNDAI";
companyNames[6]="AUDI";
companyNames[7]="MERCEDES";
companyNames[8]="DACIA";
companyNames[9]="TOYOTA";
final TreeItem<SelectedCompanyClass> treeRootItem = new TreeItem<>(SelectedCompanyClass1);
final TreeView<SelectedCompanyClass> treeView = new TreeView<>(treeRootItem);
treeRootItem.setExpanded(true);
treeView.setCellFactory(e -> new CustomCell());
VBox mainVBox = new VBox();
mainVBox.getChildren().add(treeView);
Scene scene1 = new Scene(mainVBox,1600,600);
primaryStage.setScene(scene1);
primaryStage.show();
primaryStage.centerOnScreen();
System.out.println("Start runs");
}
class CustomCell extends TreeCell<SelectedCompanyClass> {
protected void updateItem(SelectedCompanyClass SelectedCompanyClass1, boolean empty)
{
ComboBox companiesComboBox = new ComboBox();
Button addChildButton = new Button("Add Child");
Button removeButton = new Button("Remove Child");
super.updateItem(SelectedCompanyClass1,empty);
if (isEmpty()) {
setGraphic(null);
setText(null);
}
else {
HBox cellHBox = new HBox();
if (SelectedCompanyClass1!=null)
{
if (SelectedCompanyClass1.companyNameString.equals("Root"))
{
cellHBox.getChildren().addAll(companiesComboBox,addChildButton);
}
else cellHBox.getChildren().addAll(companiesComboBox,addChildButton,removeButton);
companiesComboBox.getSelectionModel().select(SelectedCompanyClass1.companyNameString);
}
setGraphic(cellHBox);
setText(null);
}
companiesComboBox.getItems().addAll((Object[]) companyNames);
addChildButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
String selection="none";
SelectedCompanyClass SelectedCompanyClass2 = new SelectedCompanyClass(selection);
if (companiesComboBox.getSelectionModel().getSelectedItem().toString()!=null) {
selection=companiesComboBox.getSelectionModel().getSelectedItem().toString();
SelectedCompanyClass2.companyNameString=selection;
}
TreeItem<SelectedCompanyClass> childNode2 = new TreeItem<>(SelectedCompanyClass2);
getTreeItem().getChildren().add(childNode2);
childNode2.setExpanded(true);
}});
removeButton.setOnAction(value -> {
//somehow i will remove the leaf/branch
});
}
}
public static void main(String[] args) {
launch(args);
}
}
Now, thanks to Slaw , i have made progress and i create new objects TreeItem as childs, but parent Node loses its ComboBox selection
UPDATE 2:
After the usefull suggestions, i finally done it, here is the code
The model Class code
package example;
import javafx.beans.property.StringProperty;
public class SelectedCompanyClass {
String companyNameString = new String();
public SelectedCompanyClass() {
companyNameString="Choose";
}
}
and the Main code
package example;
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.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author me
*/
public class Example extends Application {
String[] companyNames = new String[10];
int x=0;
#Override
public void start(Stage primaryStage) {
SelectedCompanyClass SelectedCompanyClass1 = new SelectedCompanyClass();
companyNames[0]="FORD";
companyNames[1]="MG";
companyNames[2]="LADA";
companyNames[3]="BMW";
companyNames[4]="KIA";
companyNames[5]="HYUNDAI";
companyNames[6]="AUDI";
companyNames[7]="MERCEDES";
companyNames[8]="DACIA";
companyNames[9]="TOYOTA";
final TreeItem<SelectedCompanyClass> treeRootItem = new TreeItem<>(SelectedCompanyClass1);
final TreeView<SelectedCompanyClass> treeView = new TreeView<>(treeRootItem);
treeRootItem.setExpanded(true);
treeView.setCellFactory(e -> new CustomCell());
VBox mainVBox = new VBox();
mainVBox.getChildren().add(treeView);
Scene scene1 = new Scene(mainVBox,1600,600);
primaryStage.setScene(scene1);
primaryStage.show();
primaryStage.centerOnScreen();
System.out.println("Start runs");
}
class CustomCell extends TreeCell<SelectedCompanyClass> {
protected void updateItem(SelectedCompanyClass SelectedCompanyClass1, boolean empty)
{
ComboBox companiesComboBox = new ComboBox();
Button addChildButton = new Button("Add Child");
Button removeButton = new Button("Remove");
Label objectLabel = new Label();
companiesComboBox.valueProperty().addListener((obs, oldValue, newValue) -> {
SelectedCompanyClass1.companyNameString=newValue.toString();
});
super.updateItem(SelectedCompanyClass1,empty);
if (isEmpty()) {
setGraphic(null);
setText(null);
}
else {
HBox cellHBox = new HBox();
if (SelectedCompanyClass1!=null)
{
cellHBox.getChildren().addAll(companiesComboBox,addChildButton,removeButton,objectLabel);
companiesComboBox.getSelectionModel().select(SelectedCompanyClass1.companyNameString);
}
setGraphic(cellHBox);
setText(null);
}
companiesComboBox.getItems().addAll((Object[]) companyNames);
addChildButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
String selection="none";
SelectedCompanyClass SelectedCompanyClass2 = new SelectedCompanyClass();
TreeItem<SelectedCompanyClass> childNode2 = new TreeItem<>(SelectedCompanyClass2);
getTreeItem().getChildren().add(childNode2);
childNode2.setExpanded(true);
companiesComboBox.valueProperty().addListener((obs, oldValue, newValue) -> {
SelectedCompanyClass2.companyNameString=newValue.toString();
});
}});
removeButton.setOnAction(value -> {
//somehow i will remove the leaf/branch
});
}
}
public static void main(String[] args) {
launch(args);
}
}
Best regards to all

is there any way to add button into dropdown list with textfields using controlfx jar

i have a textfield with autocomplete and i want to show button near each item appeared into that list
this is my code
List<String> s = ms.getUsernames(ms.getUser(7).getListamis());
TextFields.bindAutoCompletion(txtsearch, s);
this is the method getusernames
public List<String> getUsernames(String list_amis) {
List<String> ls = new ArrayList<>();
String [] idmember = list_amis.split("/");
for (String i : idmember) {
ls.add(getUser(Integer.parseInt(i)).getUsername());
}
return ls;
}
this is my output
i want to add a button near testing as a result i can get its ID
This is the solution I came up with. There certainly is a better way that is more elegant and works better, but I guess this would work for many situations. You would have to do something about the size of the ListView, though, and I didn't test this in an environment in which the appearing ListView might change something about the design of the rest of the UI. I suggest putting the whole thing into a PopOver or something.
import java.util.function.Predicate;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
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.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class NewFXMain extends Application {
#Override
public void start(Stage primaryStage) {
ObservableList<String> list = FXCollections.observableArrayList("one","two","three");
FilteredList<String> filteredList = new FilteredList<>(list);
VBox box = new VBox();
TextField textField = new TextField();
textField.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
filteredList.setPredicate(new Predicate<String>() {
#Override
public boolean test(String s){
return s.toLowerCase().contains(newValue.toLowerCase());
}
});
}
});
ListView listView = new ListView();
listView.setItems(filteredList);
listView.visibleProperty().bind(textField.textProperty().isNotEmpty());
listView.setCellFactory(new Callback() {
#Override
public Object call(Object param) {
ListCell cell = new ListCell(){
#Override
public void updateItem(Object item, boolean empty){
if(item != null && !empty){
super.updateItem(item, empty);
HBox contentBox = new HBox();
Label label = new Label(item.toString());
Button button = new Button("delete");
HBox separator = new HBox();
HBox.setHgrow(separator, Priority.ALWAYS);
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println(item);
}
});
contentBox.getChildren().addAll(label, separator, button);
setGraphic(contentBox);
}else{
setText(null);
setGraphic(null);
}
}
};
return cell;
}
});
box.getChildren().addAll(textField,listView);
StackPane root = new StackPane();
root.getChildren().add(box);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Autocomplete");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

how to dynamically set new TreeItems in a TreeView in JavaFX [duplicate]

I am begging with JavaFx, and I realized that I need some help to update a TreeView with some TreeItems in runtime, and it should be updated in the main window.
Here, you can see a screenshot of the two windows:
The bigger is the main window and it calls (by clicking in File >> New Project), new smaller. In the smaller window, I could get the String that is typed and than the enter button is clicked.
The trouble is: How can I show the new items created by the "new project window" (the smaller window in the pic) in the TreeView in the main window(the bigger)?
The treeview is in the left side of the main window.
I hope I was clear.
Here is the code of the controllers of these windows:
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeItem.TreeModificationEvent;
import javafx.scene.control.TreeView;
import javafx.stage.Modality;
import javafx.stage.Stage;
/**
* this class handles with the main window of our LDF Tool
* #author Vinicius
* #version 1.0
*/
public class MainController implements Initializable{
#FXML
TreeView<String> treeView;
#FXML
MenuItem newProject;
private boolean flag = false;
private NewProjectWindowController npwc;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#FXML
public void newProjectClicked(ActionEvent event){
try{
flag = true;
FXMLLoader fxml = new FXMLLoader(getClass().getResource("newProjectWindow.fxml"));
Parent root = (Parent) fxml.load();
Stage newWindow = new Stage();
newWindow.setTitle("New Project");
newWindow.initModality(Modality.APPLICATION_MODAL);
newWindow.setScene(new Scene(root));
newWindow.show();
} catch (Exception e) {
System.out.println("caiu na exceção");
}
}
/**
* to this method, choose the project's name as argument, and it will be put on the
* tree with the archives that should be created together
* #param projectName
*/
public void doTree(String projectName){
TreeItem<String> root = new TreeItem<>("projectName");
root.setExpanded(true);
//TreeItem<String> folha1 = new TreeItem<String>(projectName + " arquivo 1");
//root.getChildren().add(folha1);
treeView.setRoot(root);
}
The other controller class:
package application;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class NewProjectWindowController implements Initializable{
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#FXML
Button cancelButton;
#FXML
Button enterButton;
#FXML
TextField textInput;
private String input;
public String getInput(){
return this.input;
}
#FXML
public void cancelButtonClicked(ActionEvent event) {
Stage window = (Stage) this.cancelButton.getParent().getScene().getWindow();
window.close();
}
#FXML
public void enterButtonClicked(ActionEvent event) {
input = hasString();
Stage window = (Stage) this.enterButton.getParent().getScene().getWindow();
window.close();
}
private String hasString(){
if (this.textInput.getText().isEmpty())
return null;
return this.textInput.getText();
}
}
Please, assume that I mapped everything ok in the FXML file.
thanks
#FXML
public void newProjectClicked(ActionEvent event){
try{
flag = true;
FXMLLoader fxml = new FXMLLoader(getClass().getResource("newProjectWindow.fxml"));
Parent root = (Parent) fxml.load();
Stage newWindow = new Stage();
newWindow.setTitle("New Project");
newWindow.initModality(Modality.APPLICATION_MODAL);
newWindow.setScene(new Scene(root));
// showAndWait blocks execution until the window closes:
newWindow.showAndWait();
NewProjectWindowController controller = fxml.getController();
String input = controller.getInput();
if (input != null) {
TreeItem<String> currentItem = treeView.getSelectionModel().getSelectedItem();
if (currentItem == null) currentItem = treeView.getRoot();
currentItem.getChildren().add(new TreeItem<>(input));
}
} catch (Exception e) {
System.out.println("caiu na exceção");
}
}

Javafx split pane with treeview

Please help me to add item from addproject controller to project controller. I want to add item from addprojects controller to projectscontroller method. Please guide me to resolve this. please guide to dynamically change the right side split pane view and add tree item in treeview and show to user.
package com.define.controller;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.Event;
//import org.apache.commons.io.FileUtils;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tab;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javax.naming.Context;
import testapp.TestApp;
public class ProjectsController implements Initializable{
// #FXML private HBox fileList;
#FXML TreeView<String> Maintree ;
#FXML private AnchorPane Anchorpane;
File destinationFolder;
//Image img = new Image();
//private final Node rootIcon = new ImageView(img);
/* private final Node rootIcon = new ImageView(
new Image(getClass().getResourceAsStream("G:\\workspace\\DefineApp\\src\\images\\folder.png")));*/
File file = new File("D:\\DefineApp\\src\\images\\folder.png");
Image image = new Image(file.toURI().toString(),20,20,false,false);
private Node rootIcon = new ImageView(image);
#Override
public void initialize(URL location, ResourceBundle resources) {
File currentDir = new File("D:\\DefineApp\\src\\Documents"); // current directory
rootItem.setExpanded(true);
Maintree.setShowRoot(false);
Maintree.setRoot(rootItem);
findFiles(currentDir);
try {
changeView();
} catch (IOException ex) {
Logger.getLogger(ProjectsController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void UploadFiles() throws IOException{
DirectoryChooser directory = new DirectoryChooser();
directory.setTitle("Choose Directory");
final File selectedDirectory = directory.showDialog(null);
File sourcefolder = new File(selectedDirectory.getAbsolutePath());
String projectName = "Symbiance";
String studyName = "study1";
destinationFolder = new File("G:\\workspace\\DefineApp\\src\\"+projectName+"\\"+studyName);
if(!destinationFolder.exists()){
destinationFolder.mkdirs();
if(destinationFolder.isDirectory()){
// FileUtils.copyDirectory(sourcefolder, destinationFolder);
System.out.println("Files Copied Successfully");
}
}else{
if(destinationFolder.isDirectory()){
//FileUtils.copyDirectory(sourcefolder, destinationFolder);
System.out.println("Files Copied Successfully");
}
}
//Method call for list the files
listFiles();
}
public void listFiles(){
//fileList.setPadding(new Insets(15, 12, 15, 12));
//fileList.setSpacing(10);
File[] listOfFiles = destinationFolder.listFiles();
CheckBox[] cbs = new CheckBox[listOfFiles.length];
int i=0;
for (File file : listOfFiles) {
CheckBox cbox = cbs[i]= new CheckBox(file.getName());
i++;
}
//fileList.getChildren().addAll(cbs);
}
TreeItem<String> rootItem = new TreeItem<String>("Root");
public void findFiles(File currentDir){
//rootItem.setGraphic(rootIcon);;
TreeItem<String> subfolder;
// parent = new TreeItem<String> (parent.getValue(),rootIcon);
System.out.println("1");
File folder = new File(currentDir.getAbsolutePath());
File[] listOfFiles = folder.listFiles();
for (File file:listOfFiles) {
if(file.isDirectory()){
subfolder = new TreeItem<String> (file.getName());
rootItem.getChildren().add(subfolder);
File subFolderName = new File(file.getAbsolutePath());
File[] subFolderFiles = subFolderName.listFiles();
for(File f:subFolderFiles){
TreeItem<String> it= new TreeItem<String>(f.getName());
subfolder.getChildren().add(it);
}
}
}
}
public void changeView() throws IOException{
System.out.println("change view is called");
Anchorpane.getChildren().add(TestApp.getInstance().designChooser("com/define/views/AddProject.fxml"));
//setContent();
}
public void addProject(String name,Event e){
rootItem.getChildren().add(new TreeItem(name));
System.out.println("test check");
}
}
another controller;
package com.define.controller;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TreeItem;
import javafx.scene.text.Text;
public class AddProjectController implements Initializable{
#FXML Button yesbutton;
#FXML RadioButton projectYesRadio;
#FXML RadioButton projectNORadio;
#FXML TextField projectId;
#FXML TextField projectName;
final ToggleGroup Projectgroup = new ToggleGroup();
final File baseFolder = new File("D:\\DefineApp\\src\\Documents");
File projectFolder;
#Override
public void initialize(URL location, ResourceBundle resources) {
projectYesRadio.setToggleGroup(Projectgroup);
projectNORadio.setToggleGroup(Projectgroup);
projectYesRadio.setSelected(true);
}
public void addProject(ActionEvent e){
projectFolder = new File("D:\\DefineApp\\src\\Documents\\"+projectName.getText());
projectFolder.mkdir();
ProjectsController pt = new ProjectsController();
pt.addProject(projectName.getText(),e);
//System.out.println(projectController.Maintree.getRoot());
//.rootItem.getChildren().add(new TreeItem(projectName.getText()));
//projectController.findFiles(baseFolder);
System.out.println("test check");
}
public void radiocalled(){
//yesbutton.setVisible(false);
}
}

Resources