JavaFX ComboBox readFromFile - javafx

In JavaFX is it at all possible to fill a ComboBox with items read from a file? Basically, I have a list of all the street names in a country and I want to display them within my ComboBox as options. Thanks.
Edit:
Finally found some time to actually tackle however I got stuck when it came to loading the array into the combobox. Any help?
This is the method which reads from the file:
private String ReadTownsAndCities(String[] choice){
List<String> list = new ArrayList<>();
String s;
FileReader fr;
BufferedReader br;
try{
fr = new FileReader("TownsAndCities.txt");
br = new BufferedReader(fr);
while((s = br.readLine()) !=null){
list.add(s);
}
choice = list.toArray(new String[list.size()]);
fr.close();
}catch(FileNotFoundException exc){
System.out.println("Cannot open input file.");
}catch(IOException exc){
System.out.println("Error reading file");
}
Now I need to load it into this combobox:
//locality combo box
localityCombo = new ComboBox<>();
//localityCombo.getItems().addAll();
grid.add(localityCombo, 1,11);

Depends on what format does the file have. If it contains many lines and each line is a street name, i would read the file line by line with a WHILE-Loop and for each iteration create a new Item in your ComboBox.

Related

JavaFX ComboBox store selected item in csv file

so I am using JavFX to create a form that stores all the answers in a csv file. I need to create a dropdown menu that allows the users to select an option, which is then recorded in the csv file. I have tried a lot of different options, however I think comboBox is the best option.
I have no problem creating the ComboBox, I only run into problems when it comes to the method to get the value of the box.
Can someone help me find a solution, or suggest what another JavaFX menu I can use?
This is the code I have right now:
public VBox setFamiliar(){
Button button = new Button();
button.setOnAction(e -> toString());
familiarComboBox = new ComboBox<>();
familiarVBox = new VBox();
familiarComboBox.getItems().addAll("Irmão", "Irmã", "Avó", "Avô", "Tio", "Tia", "Pai", "Mãe");
familiarVBox.getChildren().add(familiarComboBox);
familiarVBox.getChildren().add(button);
return familiarVBox;
}
Here I set the ComboBox, this part doesnt seem to have a problem because it appears and I can select an item. I created a separate void toString() method that sets the value of a variable to the current selected item
public void toString(ActionEvent e){
familiar = familiarComboBox.getSelectionModel().getSelectedItem().toString();
}
The problem is then in the get method to get the value that was selected.
public String getIrmao(){
if(familiar.equals("Irmão")){
return "2";
}
return "0";
I also tried to do familiarComboBox.getSelectionModel().getSelectedItem().equals(), and other variations of this combination.
If I understand your requirement -- that when a user makes a choice from the "Familiar" combo box, a value should be written immediately to a CSV file -- you don't need the getIrmao() method. You simply write the value out in the action which you are calling toString(...) (not a good choice of names), but which we will rename to handleFamiliarChange(...).
Now the method becomes
public void handleFamiliarChange(ActionEvent e){
final String familiar =
familiarComboBox.getSelectionModel().getSelectedItem().toString();
FileUtils.writeToCsvFile(familiar.equals("Irmão") ? 2 : 0);
}
where FileUtils.writeToCsvFile(...) is a method that does the file writing. Note that FileUtils is a class you have created to separate out file handling concerns -- your JavaFX view class should only concern itself with views.

How to create many folders inside a main folder using treeview in JavaFX?

To make it clear, I'm creating a treeview that will instantiate itself after the user creates a folder and said folder will be added as treeitem.
I currently have this:
TreeView treeView = new TreeView();
// Create new folder
MenuItem menuItem1 = new MenuItem("Create New Folder");
menuItem1.setOnAction(e -> {
System.out.println("Please name your directory:");
Scanner in = new Scanner(System.in);
String strFolder = in. nextLine();
createFolder(strFolder); // Create folder
TreeItem rootFolder = new TreeItem(strFolder); // Create new TreeItem
treeView.setRoot(rootFolder); // Replace old folder with new one
// rootFolder.getChildren().add(rootFolder);
// rootItem.getChildren().add(rootFolder);
});
After the treeView, I declared a new Menu Item that which will trigger an event after being clicked on.
The event will ask the user for a name to use as the root folder for the treeView. Now thats working fine.
Now what I'm having troubles with, is how to create more folders inside the root folder created and display them as subfolders in the treeView?
So far my code only does replace the old root folder by the new one created. Instead of setting the root folder again, how can i make it so it just adds those folders inside the first one and display them - again - in the treeView as subfolders?
Did I explain myself?
Thanks.
Simply add TreeItem(s) to the child list of the TreeItem. The following example replaces the root, if no items are selected and otherwise adds the new item as a child of the selected one:
TreeView<String> treeView = new TreeView<>(); // never use raw type without good reason
// Create new folder
MenuItem menuItem1 = new MenuItem("Create New Folder");
menuItem1.setOnAction(e -> {
TextInputDialog dialog = new TextInputDialog(); // replacing console input with dialog here
dialog.setHeaderText("Please name your directory:");
String strFolder = dialog.showAndWait().orElse(null);
if (strFolder != null) {
TreeItem<String> newFolder = new TreeItem<>(strFolder); // Create new TreeItem
TreeItem<String> selection = treeView.getSelectionModel().getSelectedItem();
createFolder(strFolder); // Create folder ; TODO: make dependent on parent???
if (selection == null) {
treeView.setRoot(newFolder); // Replace old folder with new one
} else {
selection.getChildren().add(newFolder);
selection.setExpanded(true); // make sure we're able to see the new child
}
}
});

Fragment showing Old Data

I am new to android programming. I am implementing functionality to scan particular Inventory Item and search for the barcode if it already exists in an ArrayList. If it exists then I am replacing the current Scan fragment with the InvnetoryFound Fragment in which I have option to update quantity and completely remove item from ArrayList.
The issue I am facing is, after removing Inventory when I scan again for different Inventory barcode, upon successful scan, it is showing InventoryFound Fragment with old data that was removed from ArrayList. Below is my code:
Test ArrayList Code:
public static String[] inve = new String[5];
public static ArrayList<String[]> inventory_list = new ArrayList<String[]>();
inve[0] = "INV45879";
inve[1] = "Bridge Support Pipe";
inve[2] = "Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications.Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications.";
inve[3] = "0885370720679";
inve[4] = "2";
inventory_list.add(inve);
inve = new String[5];
inve[0] = "INV45880";
inve[1] = "Cement";
inve[2] = "Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications";
inve[3] = "9771234567003";
inve[4] = "8";
inventory_list.add(inve);
If scan is successful it calls below function to replace fragment:
private static void showFragment(Fragment fragment, String back_option) {
try {
// start transition
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
//if fragment Inventory is found then pass data to fragment
if(back_option.equals("inventoryFound")){
//sends found inventory list data to fragment
String[] inv_data = inventory_list.get(inventory_index);
Bundle bundle = new Bundle();
bundle.putStringArray("inventory_data",inv_data);
bundle.putInt("inventory_index",inventory_index);
inventoryFoundFragment.setArguments(bundle);
back_option = "null";
// replace fragment
if (!back_option.equals("null")) // with back option
ft.replace(R.id.frag_content, fragment).addToBackStack(back_option);
else // no back option
ft.replace(R.id.frag_content, fragment);
// commit
ft.commit();
}
catch(Exception e){
out("PROBLEM SHOWING FRAGMENT!!!"+e.getMessage());
}
}
InventoryFound fragment populates data and works fine. Below is the code when I click on Remove populated Inventory:
public void removeInventory(){
Shared.inventory_list.remove(inventory_index);
Toast.makeText(mContext,"Inventory "+inventory_index+" Removed Successfully!", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(this);
ft.replace(R.id.frag_content, new ScanFragment());
ft.commit();
}
It is removing successfully but when I scan it again e.g. for barcode "0885370720679" it shows the previous data on InventoryFound fragment. I have debugged it in Logcat (Log.d) and I am able to see correct data but it is not displaying in fragment.
any suggestions or guidance will be appreciated.
I found the solution for this problem.
When Fragment is in foreground, it calls onResume() method. In this method I call user-defined function which re-sets the data for Fragment fields. I don't know if it's a correct to way to fix this issue but it's working for me now!

JavaFX architecture in building dynamic "rows"

I have an application that I am building that has a table in it, I'm not using a tableview to build this table because I need each row to be able to expand similar to an accordion. I was able to achieve what I need by using a timeline and looping through the data and building each row (its kind of crude right now since I'm still working with dummy data eventually it will be a list iterator and not just a for loop) but I'm not happy with how its done. There are a lot of default values that will never change so I don't really need to set them in my worker class every time, I decided to just add them to the object class that I put together. So basically, at a high level it looks something like this:
for (int i = 0; i < 30; i++) {
RowBuilder builder = new RowBuilder(tableBox, i);
try {
builder.run();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'm passing it the parent which is a VBox - tableBox, then I'm passing the count for later use.
Inside the RowBuilder I'm getting a new instance of the object DashboardRow which has all the defaults set in it, then I'm setting the data for each row and returning the DashboardRow.
Here is an example of a getter setting values in the DashboardRow
public HBox getMainRow() {
mainRow.setAlignment(Pos.CENTER_LEFT);
mainRow.setPrefHeight(60);
mainRow.setMinHeight(60);
mainRow.setMaxHeight(60);
mainRow.setPrefWidth(-1);
mainRow.setStyle("-fx-background-color:#FFFFFF;");
return mainRow;
}
Inside the DashboardRow class I have a ton of new objects being created for every element I need in the row. There are 21 for each row, mostly VBox, HBox and StackPane to build the actual row, the rest are just labels and buttons.
This is what is looks like so far. Opened and closed states.
Is there a better way to dynamically build things like this in javafx? I'm basically pulling data from a database and looping through that data to populate a row.
I can't comment but it may be an answer anyway. Why can't you use the setGraphic method of a custom table cell and put the accordion node in a table. setGraphic takes any kind of node.
It sounds simpler than what you're doing.
I just tried it out with the Oracle sample and it works great.
I added
Callback<TableColumn<Person, String>, TableCell<Person, String>> accCellFactory
= new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
#Override
public TableCell call(TableColumn p) {
TitledPane t1 = new TitledPane("T1", new Button("B1"));
TitledPane t2 = new TitledPane("T2", new Button("B2"));
TitledPane t3 = new TitledPane("T3", new Button("B3"));
Accordion accordion = new Accordion();
accordion.getPanes().addAll(t1, t2, t3);
TableCell tc = new TableCell();
tc.setGraphic(accordion);
return tc;
}
};
and changed this line firstNameCol.setCellFactory(accCellFactory);
and I get
Of course you might want something other than buttons but I just copied the Accordion sample from the javadoc.

iTextSharp - MVC / HTMLWorker one string to add to a paragraph

I am sending the contents of Telerik MVC Editor to the controller using Ajax as a string:
I comes out as:
"<strong>Hello world!</strong> <object height=\"1\" id=\"plugin0\" style=\"position:absolute;z-index:1000;\" type=\"application/x-dgnria\" width=\"1\"><param name=\"tabId\" value=\"{84594B7B-865F-4AD7-A798-294A8B0EB376}\" /></object>"
In the controller, I save the string to a session variable using the following:
string comments = HttpUtility.HtmlDecode(Text);
MySession.Current.pdfText = comments;
I can convert it to PDF using
.....
HTMLWorker parser = new HTMLWorker(document);
.......
However I could not add any other paragraphes to the same page, it makes a new page.
I tried to use the following to make a new paragraph using HTMLWORK:
string PDFText = MySession.Current.pdfText;
string PDFText1 = HTMLWorker.Parse(PDFText);
StringReader reader = new StringReader(PDFText1);
paragraph.Add(reader);
I got these errors:
cannot convert from 'System.IO.StringReader' to 'string', and
The best overloaded method match for 'iTextSharp.text.html.simpleparser.HTMLWorker.Parse(System.IO.TextReader)' has some invalid arguments, and
The best overloaded method match for 'iTextSharp.text.Phrase.Add(string)' has some invalid arguments
I would appreciate your suggestions, thanks in advance.
I have worked a lot on iTextSharp and I usually follow the approach of creating a table or nested tables; if needed, with multiple rows and columns and using colspan to spread out my content on the page.
PdfPTable table = new PdfPTable(1); //Create a new table with one column
PdfPCell cell = new PdfPCell(); //Create an empty cell
StyleSheet style = new StyleSheet(); //Declare a stylesheet
style.LoadTagStyle("h1", "color", "red"); //Create styles for your html tags which you think will be there in PDFText
ArrayList objects = HTMLWorker.ParseToList(new StringReader(PDFText),style); //This transforms your HTML to a list of PDF compatible objects
for (int k = 0; k < objects.Count; ++k)
{
cell.AddElement((IElement)objects[k]); //Add these objects to cell one by one
}
table.AddCell(cell); //Add cell to table
document.add(table) //Add table to the document
try it out with just the paragraph once as you were trying in the question. otherwise this approach will definitely not result in a new page.
EDIT:
please see the updated code
PdfPTable table = new PdfPTable(2); //Create a new table with one column
PdfPCell cellLeft = new PdfPCell(); //Create an empty cell
StyleSheet style = new StyleSheet(); //Declare a stylesheet
style.LoadTagStyle("h1", "color", "red"); //Create styles for your html tags which you think will be there in PDFText
List<IElement> objects = HTMLWorker.ParseToList(new StringReader(PDFText),style); //This transforms your HTML to a list of PDF compatible objects
for (int k = 0; k < objects.Count; ++k)
{
cellLeft.AddElement((IElement)objects[k]); //Add these objects to cell one by one
}
table.AddCell(cellLeft); //Add cell to table
string url = "http://localhost:1713/PDF/Images/sample.jpg"; //Image Path(can give local machine path for testing)
PdfPCell cellRight = new PdfPCell();
Image jpg = Image.GetInstance(new Uri(url));
cellRight.AddElement(jpg);
table.AddCell(cellRight);
document.add(table);
Please google for padding, margins, borders and coloring etc..

Resources