Get a path in a TextField from an event - java

I would like to choose a file in my app and then write its path in a Textfield and use it as a Variable for my main app.
I did my interface and add a few things like when I press a button I choose a file but I don't know how to get that path.
Here is my main app code :
package ch.makery.adress;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.Parent;
public class MainApp extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent parent = FXMLLoader.load(getClass().getResource("PersonOverview.fxml"));
Scene scene = new Scene(parent);
stage.setTitle("Appication Extraction et remplissage Excel");
stage.setScene(scene);
stage.show();
}
}
And here my controller class :
package ch.makery.adress;
import java.awt.FileDialog;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
public class HexaController implements Initializable {
static JFrame fileDialog;
#FXML
private ComboBox<String> hexa;
ObservableList<String> list = FXCollections.observableArrayList();
#FXML
private void dar(ActionEvent event){
FileDialog fd1=new FileDialog(fileDialog,"Choisissez un fichier d'entree",FileDialog.LOAD);
fd1.setDirectory("C:\\");
fd1.setVisible(true);
String filename1=fd1.getFile();
String Directory1=fd1.getDirectory();
String path1=Directory1 + filename1;
}
#FXML
private void modele(ActionEvent event){
JFrame parentFrame=new JFrame();
FileDialog filechooser = new FileDialog (parentFrame, "Choisir un modèle Excel à copier",FileDialog.LOAD);
filechooser.setDirectory("C:\\");
filechooser.setVisible(true);
String directory_copy = filechooser.getDirectory();
String name_copy= filechooser.getFile();
String path_copy = (directory_copy+name_copy);
}
#FXML
private void sortie (ActionEvent event){
JFrame parentFrame2=new JFrame();
FileDialog filechooser2 = new FileDialog (parentFrame2, "Choisir une destination d'enregistrement",FileDialog.SAVE);
filechooser2.setDirectory("C:\\");
filechooser2.setVisible(true);
String directory_save = filechooser2.getDirectory();
String name_save= filechooser2.getFile();
String path_save = (directory_save+name_save+".xls");
}
#FXML
private void annuler (ActionEvent event){
System.exit(0);
}
#FXML
private ComboBox<Integer>methode;
ObservableList<Integer>nombre = FXCollections.observableArrayList();
#FXML
private TextField entree;
#FXML
private TextField excel;
#FXML
private TextField sortie;
public HexaController(){
}
public void initialize(URL url,ResourceBundle rb){
list.add(new String("OUI"));
list.add(new String("NON"));
hexa.setItems(list);
nombre.add(new Integer(1));
nombre.add(new Integer(2));
nombre.add(new Integer(3));
nombre.add(new Integer(4));
nombre.add(new Integer(5));
methode.setItems(nombre);
}
}
What should I do next to make it work ? Don't know where to start.
Thanks

as it is a JavaFX application , i suppose that you will start an app per user so you wont have issues with global information shared in the memory.
i) the first approach is to have a private String latestFilePath , for your example , in your HexaController and when the user does a file opening , you could take the filePath and pass it on the String field
String directory_save = filechooser2.getDirectory();
String name_save= filechooser2.getFile();
this.latestFilePath = directory_save+name_save;
So later you can use it anywhere you want , with a simple if statement to check whether it is null
ii) as a second approach , which can be an extension of the above , you could simply take the filePath and set it on your text field
String filename1=fd1.getFile();
String Directory1=fd1.getDirectory();
String path1=Directory1 + filename1;
entree.setText(path1);

Related

Java fx Changing the Color of a String

In my Program i have to change the color of a sample string by clicking on the radio Buttons. But i keep getting errors every time i click on them. i keep getting this error. I am also using e(fx)clipse to code this.
Caused by: java.lang.ClassCastException:
javafx.graphics#10.0.2/javafx.scene.paint.Color cannot be cast to
javafx.graphics#10.0.2/javafx.scene.text.Text at
employee.view.MainController.colorRadioButtonSelected(MainController.java:83)
package employee.view;
import javafx.beans.value.ChangeListener;
import javafx.scene.paint.Paint;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
public class MainController {
#FXML
private BorderPane myPane;
#FXML
private RadioButton blackRadioButton;
#FXML
private ToggleGroup colorToggleGroup;
#FXML
private RadioButton redRadioButton;
#FXML
private RadioButton blueRadioButton;
#FXML
private RadioButton greenRadioButton;
#FXML
private ListView<String> mylistView;
#FXML
private CheckBox boldCheckBox;
#FXML
private CheckBox italicCheckBox;
String Text;
Text sample=new Text(50,300,"SAMPLE");
FontWeight weight = FontWeight.NORMAL; // FontWeight.BOLD is boldface
FontPosture posture = FontPosture.REGULAR; // FontPosture.ITALIC is italic
int size=18;
boolean fontBold = false;
boolean fontItalic = false;
public void initialize() {
blackRadioButton.setUserData(Color.BLACK);
redRadioButton.setUserData(Color.RED);
greenRadioButton.setUserData(Color.GREEN);
blueRadioButton.setUserData(Color.BLUE);
myPane.getChildren( ).add( sample );
sample.setFont(Font.font("Verdana", weight, posture, size));
}
#FXML
void boldCheckBoxSelected(ActionEvent event) {
}
#FXML
void colorRadioButtonSelected(ActionEvent event) {
sample= (javafx.scene.text.Text) colorToggleGroup.getSelectedToggle().getUserData();
}
#FXML
void italicCheckBoxSelected(ActionEvent event) {
}
}
You set the data as Color
blackRadioButton.setUserData(Color.BLACK);
redRadioButton.setUserData(Color.RED);
greenRadioButton.setUserData(Color.GREEN);
blueRadioButton.setUserData(Color.BLUE);
But you try to cast it as Text
(javafx.scene.text.Text) colorToggleGroup.getSelectedToggle().getUserData();
To fix this you can use a switch statement or multiple if statements to set sample object depending on which colour is selected. Example if statement:
if ((Color) colorToggleGroup.getSelectedToggle().getUserData() == Color.BLUE) {
sample = new Text(50, 300, "Something");
}
Alternatively you can set the data for the radio buttons as Text, for example:
blueRadioButton.setUserData(new Text(50, 300, "Something"));

(JavaFX) How do I initialize my TreeView?

Im not able to initialize my treeview,my fx:id is right but the output just gives me a blank treeview.
I am using scene builder with fxml controllers.
This is my Fxml Controller.
///////////////////////////////////////////////////////////////////
import java.net.URL;
import static java.time.Clock.system;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
/**
*
* #author Man Eesh
*/
public class FXMLDocumentController implements Initializable {
#FXML
private TreeView<String> treeView;
#FXML
private Label label;
#FXML
private void handleButtonAction(ActionEvent event){
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// System.out.print("here");
label.setText("Hello World!");
TreeItem<String> root = new TreeItem<>("Root Node");
root.setExpanded(true);
System.out.print("here");
root.getChildren().addAll(
new TreeItem<>("Item 1"),
new TreeItem<>("Item 2"),
new TreeItem<>("Item 3")
);
treeView.setRoot(root);
}
}

How do you make the contents of a ListView an ArrayList?

I am trying to make a to do list javafx class and I'm using a list view to do it but I want to set the contents of the list view with an array list I made. SO basically that once I open the program you get a text field and button to add items to the arraylist which is the listview. Anyway I could replace the arraylist with the listview and just directly add the items to that? I'm a newbie programmer by the way.
package learning;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class ToDoList extends Application{
private ArrayList<String> doList=new ArrayList<>();
private String text="";
public void start(Stage primaryStage){
primaryStage.setTitle("2DoList");
TextField userTextField = new TextField();
Button enter=new Button("Add");
enter.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
text= userTextField.getText();
doList.add(text);
userTextField.setText("");
text="";
}
});
ListView<String> root=new ListView<String>((ObservableList) doList);
Scene scene=new Scene(root,250,500);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Create an ObservableList instead of an ArrayList:
private ObservableList<String> doList = FXCollections.observableArrayList();
and then you can do
ListView<String> root=new ListView<String>(doList);

java fx imageslideshow using animations

i'm trying to make simple slideshow using java fx. I'm implementing methods which allow me after pressing button to show one image after another until list is over.
For now i have a code like this...it works but it shows images too fast i dont know why.Maybe someone can help me and tell me how can i slow down this timeline variable or timer.thanks in advance:
package pl.gallery.controller;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import pl.gallery.model.ImageParser;
public class MainPaneController implements Initializable {
#FXML
private BorderPane borderPane;
#FXML
private Button nextButton;
#FXML
private MenuBar menuBar;
#FXML
private AnchorPane anchorPaneTop;
#FXML
private HBox hBox;
#FXML
private Button previousButton;
#FXML
private MenuItem openFolder;
#FXML
private AnchorPane anchorPaneCenter;
#FXML
private ImageView imageView;
#FXML
private Button slideShowButton;
#FXML
private Menu menu;
private Image image;
private ImageParser parser;
private ObservableList<Image> imagesList;
private int indexPrev = 0;
private int indexNext = 0;
private Timeline timeline;
private AnimationTimer timer;
//variable for storing actual frame
private Integer i=0;
#Override
public void initialize(URL location, ResourceBundle resources)
throws IndexOutOfBoundsException {
parser = new ImageParser();
imagesList = FXCollections.observableArrayList();
DirectoryChooser dc = new DirectoryChooser();
openFolder.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
/*
* parser = new ImageParser(); imagesList = new
* ArrayList<Image>(); DirectoryChooser dc = new
* DirectoryChooser(); File dir = dc.showDialog(new Stage());
* parser.createFileList(dir);
*
*
* imagesList.add(new Image(parser.getFilesList().get(0)
* .toURI().toString())); imageView.setImage(imagesList.get(0));
*/
File dir = dc.showDialog(new Stage());
imagesList = parser.createImagesListFromFileList(dir);
imageView.setImage(imagesList.get(0));
}
});
slideShowButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
Duration duration = new Duration(1000);
timeline.setDelay(duration);
timer = new AnimationTimer() {
#Override
public void handle(long l) {
imageView.setImage(imagesList.get(i));
i++;
}
};
timeline.play();
timer.start();
}
});
}
}

Auto scroll down a TextArea

I have a TextArea that doesn't scroll down when I add text in it. I thought using this answer, but my TextArea is connected to a StringProperty like this :
consoleTextArea.textProperty().bind(textRecu);
So the answer doesn't work for me, is there another way to make my TextArea scroll down every time I update it by the binding?
Here is fast demo of what i meant in comment about adding listener to the textRecu. Yep consoleTextArea.textProperty() can't be changed because of a binding. But textRecu has no binding => can be changed and we can add listener to it.
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private StringProperty textRecu = new SimpleStringProperty();
private TextArea consoleTextArea = new TextArea();
#Override
public void start(Stage primaryStage) throws Exception{
VBox root = new VBox();
Button button = new Button("Add some text");
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
//here you change textRecu and not consoleTextArea.textProperty()
textRecu.setValue(textRecu.getValue() +"New Line\n");
}
});
root.getChildren().addAll(consoleTextArea, button);
consoleTextArea.textProperty().bind(textRecu);
//here you also add listener to the textRecu
textRecu.addListener(new ChangeListener<Object>() {
#Override
public void changed(ObservableValue<?> observable, Object oldValue,
Object newValue) {
// from stackoverflow.com/a/30264399/1032167
// for some reason setScrollTop will not scroll properly
//consoleTextArea.setScrollTop(Double.MAX_VALUE);
consoleTextArea.selectPositionCaret(consoleTextArea.getLength());
consoleTextArea.deselect();
}
});
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Categories

Resources