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");
}
}
Related
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);
}
}
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);
}
}
I am attempting to switch scenes from a login screen to the main screen of my program but whenever I try to switch scenes after clicking login, I get the following error.
"Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException"
I've messed around with my code and try to change some things to get different results but no dice. This is my first time doing a GUI so any help would be appreciated.
package pwmanager;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
/**
*
* #author 176878
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Button loginButton;
#FXML
Stage prevStage;
Stage currentStage;
public void setPrevStage(Stage stage){
this.prevStage = stage;
}
#FXML
public void getPrevStage(Stage stage){
this.currentStage = prevStage;
}
#FXML
public void loginButtonAction(ActionEvent event) throws IOException {
System.out.println("You clicked me, logging in!");
setPrevStage(prevStage);
Stage stage = new Stage();
try{
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainScreen.fxml"));
GridPane mainScreen = (GridPane) loader.load();
Scene scene = new Scene(mainScreen);
stage.setScene(scene);
stage.setTitle("Password Manager");
stage.show();
prevStage.hide();
}
catch(IOException e){
System.out.println("Did not load right");
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
I have two scenes in my javaFx project .. the first one Language.fxml has a button which on click changes the scene to allDevices.fxml .. but it throws NullPointerException saying "Location is required" although both of the fxml files are in the same path !!
that's my LanguageController.java
package astrolabe;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
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.stage.Stage;
/**
*
* #author Ahmed Fawzy
*/
public class LanguageController implements Initializable {
#FXML
private Button arabic ;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
arabic.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
try{
Node node=(Node) event.getSource();
Stage stage=(Stage) node.getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("allDevices.fxml"));/* Exception */
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
}
The problem solved by adding the package name before the fxml file name !
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);
}