What would be the right way to encrypt a JSON file on a system using Java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 hours ago.
This post was edited and submitted for review 1 hour ago.
Improve this question
I understand clearly that this kind of question has been submitted on StackOverflow. But...
Everything that i could get my eyes on (including other websites) is either :
not fulfilling the requirements (that i have)
has comments revoking answers, even accepted ones
has what i call « fine prints » making it suddenly utterly complicated to implement
uses third party libraries that i can’t be sure if they are still maintained
I think it is time to update this kind of question and remove dust.
I’m looking for a simple and efficient method to encrypt a JSON file on a system.
The requirements :
The file is stored on the host system (Win : AppData / Linux : home)
It should be decrypted with a user password.
The target system is isolated from Internet.
If something goes wrong on one JSON entry the rest of the file should be recoverable
in case of a leaked file, the attacker should not be able to use « dictionary / brute force » tools that easily.
It shouldn't use tons of libraries (stay simple)
So as of 2023 what would be the right way to encrypt a JSON file on a system using Java ?
("Right way" as being confident on the security matters)
The final goal is to provide an answer that anyone with basic encryption understanding can find here and use. Anyone should be able to follow the steps to implement it without being the specialist. The solution doesn't have to be the "Ultimate One" as there is none in this area. It will be updated upon changes on those matters. The solution should provide a "suffisent level of confidence" (meaning people agree on that).
Here is a little JavaFx project you can modify and play around with it.
Remember the encrypted file is saved on the host system in the end. Not like this example.
Main class:
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
FXMLLoader flObj = new FXMLLoader(getClass().getResource("encrypt.fxml"));
Parent pflObj = flObj.load();
Scene sceneScrMain = new Scene(pflObj);
primaryStage.setScene(sceneScrMain);
primaryStage.setTitle("StackOverflow question : How to encrypt a JSON file with a password");
EncryptController ecObj = (EncryptController) flObj.getController();
ecObj.resetForm();
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Controller
package application;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
public class EncryptController {
#FXML
private TextArea textAreaOriginal;
#FXML
private TextArea textAreaDecrypted;
#FXML
private TextArea textAreaEncrypted;
#FXML
private Button buttonRun;
#FXML
private Button buttonReset;
/**
*
*/
public void resetForm() {
this.textAreaOriginal.setText("This is the string to encrypt ### #§%îµ%¨£*-+ ###");
this.textAreaEncrypted.setText("");
this.textAreaDecrypted.setText("");
}
#FXML
private void buttonResetAction(){
this.resetForm();
}
#FXML
private void buttonRunAction(){
// Your code here
this.textAreaEncrypted.setText("There should be something here.");
this.textAreaDecrypted.setText("There should be something here that is exactly like the original.");
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefWidth="512.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.EncryptController">
<children>
<GridPane hgap="8.0" layoutX="-61.0" layoutY="-100.0" vgap="8.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columnConstraints>
<ColumnConstraints hgrow="ALWAYS" minWidth="128.0" />
<ColumnConstraints hgrow="ALWAYS" minWidth="128.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints vgrow="NEVER" />
<RowConstraints minHeight="10.0" prefHeight="30.0" />
<RowConstraints vgrow="ALWAYS" />
<RowConstraints vgrow="NEVER" />
</rowConstraints>
<children>
<Button fx:id="buttonRun" maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#buttonRunAction" text="Run" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextArea fx:id="textAreaEncrypted" minWidth="64.0" prefHeight="128.0" GridPane.rowIndex="3" />
<TextArea fx:id="textAreaDecrypted" minWidth="64.0" prefHeight="128.0" GridPane.columnIndex="1" GridPane.rowIndex="3" />
<Button fx:id="buttonReset" maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#buttonResetAction" text="Reset" GridPane.columnIndex="1" GridPane.rowIndex="4" />
<Label text="Encrypted" GridPane.rowIndex="2" />
<Label text="Decrypted" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<TextArea fx:id="textAreaOriginal" maxHeight="64.0" minWidth="64.0" GridPane.columnSpan="2147483647" />
</children>
<padding>
<Insets bottom="8.0" left="8.0" right="8.0" top="8.0" />
</padding>
</GridPane>
</children>
</AnchorPane>

A JSON file is just a regular text file in the end, and regular text is encrypted rather easily. You could just use AES with a custom key to encrypt the file, save it to disk, and decrypt it once needed.
// encrypt:
String fileContents = """
{
"some": "example",
"json": [
"file"
]
}
""";
// hash key with sha256 to make sure key is always the same valid length for aes
byte[] key = MessageDigest.getInstance("SHA-256").digest("your key here".getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] bytes = cipher.doFinal(fileContents.getBytes(StandardCharsets.UTF_8));
// write bytes out to file
// decrypt:
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] decryptedBytes = cipher.doFinal(bytes);
String originalJson = new String(decryptedBytes);

Related

Data I fetched from an XML file in JavaFX doesn't show up in TableView [duplicate]

OK, new to java by several weeks, but have been programming for 30 years. The following code executes, but only the first column is showing anything. The data object is showing multiple rows of data, with fields of data that are filled in. I'm sure I'm missing something, and have looked through similar questions on here.
APVoucher_batchgridController.java
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author kmitchell
*/
public class APVoucher_batchgridController implements Initializable {
public TableView tblMainList;
public TableColumn colDateEntered;
public TableColumn colCreatedBy;
public TableColumn colDescription;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
public void opentables(ActionEvent event) {
Object forName = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("DateEntered"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("cDesc"));
colCreatedBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("CreatedBy"));
try {
// load the driver into memory
forName = Class.forName("jstels.jdbc.dbf.DBFDriver2");
} catch (ClassNotFoundException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conn = DriverManager.getConnection("jdbc:jstels:dbf:e:\\keystone-data\\keyfund\\seymour\\keyfund.dbc");
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (conn != null) {
try {
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (stmt != null) {
// execute a query
try {
ObservableList<Object> data = FXCollections.observableArrayList();
rs = stmt.executeQuery("SELECT denteredon, cdesc, ccreatedby FROM apvbatch WHERE ldeleted = false ORDER BY denteredon DESC");
while (rs.next()) {
String enteredon = rs.getString("denteredon");
String desc = rs.getString("cdesc");
String createdby = rs.getString("ccreatedby");
sresult row = new sresult(createdby, enteredon, desc);
data.add(row);
}
tblMainList.setItems(data);
tblMainList.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class sresult {
private String DateEntered;
private String EnteredBy;
private String cDesc;
public sresult(String T, String d, String c) {
this.EnteredBy = T;
this.DateEntered = d;
this.cDesc = c;
}
public String getEnteredBy() {
return EnteredBy;
}
public void setEnteredBy(String T) {
EnteredBy = T;
}
public String getDateEntered() {
return DateEntered;
}
public void setDateEntered(String d) {
DateEntered = d;
}
public String getcDesc() {
return cDesc;
}
public void setcDesc(String c) {
cDesc = c;
}
}
}
and APVoucher_batchgrid.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" fx:id="batchlistform" prefHeight="400.0" prefWidth="600.0" styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="keystone.APVoucher_batchgridController">
<children>
<BorderPane layoutX="0.0" layoutY="0.0" prefHeight="400.0" prefWidth="600.0">
<center>
<AnchorPane prefHeight="-1.0" prefWidth="-1.0">
<children>
<Pane layoutX="0.0" layoutY="0.0" prefHeight="53.0" prefWidth="580.0">
<children>
<Label layoutX="7.0" layoutY="9.0" prefWidth="202.0" text="AP Vouchers Batch List">
<font>
<Font name="System Bold" size="14.0" />
</font>
</Label>
<Button fx:id="btnClose" cancelButton="true" layoutX="513.0" layoutY="27.0" mnemonicParsing="false" text="Close" />
<Button id="btnClose" fx:id="apvRefresh" cancelButton="true" layoutX="185.0" layoutY="27.0" mnemonicParsing="false" onAction="#opentables" text="Refresh" />
</children>
</Pane>
<TableView fx:id="tblMainList" layoutX="0.0" layoutY="53.0" prefHeight="323.0" prefWidth="580.0">
<columns>
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="91.0" text="Date Entered" fx:id="colDateEntered" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="100.0" text="Created By" fx:id="colCreatedBy" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="261.0" text="Description" fx:id="colDescription" />
</columns>
</TableView>
</children>
</AnchorPane>
</center>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</BorderPane>
</children>
<stylesheets>
<URL value="#apvoucher_batchgrid.css" />
</stylesheets>
</AnchorPane>
THANK YOU for the answer. Way to many years in case insensitive languages. This has been a quick and dirty exercise for me to learn java and the latest & greatest stuff or as I like to say New Exciting Technology (NExT!)
For anyone looking at the answer and still not completely clued in, here are the changes that made the code work properly.
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("Denteredon"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("CDesc"));
colEnteredBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("Ccreatedby"));
public class sresult {
private String Denteredon;
private String Ccreatedby;
private String CDesc;
public sresult(String T, String d, String c) {
this.Ccreatedby = T;
this.Denteredon = d;
this.CDesc = c;
}
public String getCcreatedby() {
return Ccreatedby;
}
public void setCreatedby(String T) {
Ccreatedby = T;
}
public String getDenteredon() {
return Denteredon;
}
public void setDenteredon(String d) {
Denteredon = d;
}
public String getCDesc() {
return CDesc;
}
public void setCDesc(String c) {
CDesc = c;
}
}
}
This question is really a duplicate of: Javafx PropertyValueFactory not populating Tableview, but I'll specifically address your specific case, so it's clear.
Suggested solution (use a Lambda, not a PropertyValueFactory)
Instead of:
aColumn.setCellValueFactory(new PropertyValueFactory<Appointment,LocalDate>("date"));
Write:
aColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
For more information, see this answer:
Java: setCellValuefactory; Lambda vs. PropertyValueFactory; advantages/disadvantages
How do you use a JavaFX TableView with java records?
demonstrates replacing PropertyValueFactory with lambda expressions.
Solution using PropertyValueFactory
The lambda solution outlined above is preferred, but if you wish to use PropertyValueFactory, this alternate solution provides information on that.
Background
PropertyValueFactory uses reflection to determine the methods to get and set data values as well as to retrieve bindable properties from your model class. The pattern followed is:
PropertyValueType getName()
void setName(PropertyValueType value)
PropertyType nameProperty()
Where "name" is the string specified in the PropertyValueFactory constructor. The first letter of the property name in the getter and setter is capitalized (by java bean naming convention).
Why your application doesn't work
You have these three expressions:
new PropertyValueFactory<sresult, String>("DateEntered")
new PropertyValueFactory<sresult, String>("cDesc")
new PropertyValueFactory<sresult, String>("CreatedBy")
For your sample properties, the PropertyValueFactory will look for these methods:
"DateEntered" => getDateEntered()
"cDesc" => getCDesc()
"CreatedBy" => getCreatedBy()
And you have these three getters on your sresult class:
getDateEntered()
getcDesc()
getEnteredBy()
Only getDateEntered() is going to be picked up by the PropertyValueFactory because that is the only matching method defined in the sresult class.
Advice
You will have to adopt Java standards if you want the reflection in PropertyValueFactory to work (the alternative is to not use the PropertyValueFactory and instead write your own cell factories from scratch).
Adopting Java camel case naming conventions also makes it easier for Java developers to read your code.
Some times columns doesn't show data because of column names. eg,
new PropertyValueFactory<sresult, String>("cDesc")
and getter is getcDesc cDesc column may not display data. If you change code to
new PropertyValueFactory<sresult, String>("CDesc")
and getter is getCDesc CDesc column may display data.
For anyone else who still wasn't getting it after going through the above, my problem was that I wasn't specifying my setters with the "public final" designation.

Explain why FXML objects were null

I came across a problem in my code that all the objects that were related to the FXML file for a controller class were null even though the styling from the FXML was working and all the fx:id tags were the same. Here is the FXML code:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<VBox xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
alignment="center"
spacing="10"
prefHeight="750"
prefWidth="1000"
style="-fx-background-color: lightslategray">
<padding><Insets top="0" bottom="10" left="10" right="10"></Insets></padding> <!-- Set the padding at 10px for each side of the window -->
<Label fx:id="titleLabel" style="-fx-font-weight: bold; -fx-font-size: 32;" wrapText="true" text="Deck Title"/>
<HBox spacing="10">
<Button fx:id="backButton" text="Back" prefWidth="50"/>
<ProgressBar fx:id="progressIndicator" GridPane.columnIndex="0" GridPane.rowIndex="0" prefWidth="920" progress="0.0"/>
</HBox>
<HBox spacing="20">
<Label fx:id="qLabel" style="-fx-background-color: white; -fx-border-color: black" prefWidth="480" prefHeight="400" wrapText="true"/>
<Label fx:id="aLabel" style="-fx-background-color: white; -fx-border-color: black; -fx-cursor: hand" prefWidth="480" prefHeight="400" wrapText="true" text="Click here to reveal the answer" onMouseClicked="#updateAnswer"/>
</HBox>
<HBox spacing="780">
<Button fx:id="incorrectButton" text="Incorrect" prefWidth="100"/>
<Button fx:id="correctButton" text="Correct" prefWidth="100"/>
</HBox>
</VBox>
Here is the code for the controller class:
public class openCardsController {
#FXML Button backButton;
#FXML ProgressBar progressIndicator;
#FXML Label qLabel;
#FXML Label aLabel;
#FXML Label titleLabel;
#FXML Button incorrectButton;
#FXML Button correctButton;
public void openCards() throws IOException, ParseException {
Stage window = Main.getStage();
window.setWidth(1000);
window.setHeight(750);
// Had to swap Parent root = FXMLLoader.load(getClass().getResource("./mainPage.fxml")); for the following lines
File file = new File(System.getProperty("user.dir") + "/src/flashcardApplication/openCardsPage.fxml");
FXMLLoader loader = new FXMLLoader(file.toURI().toURL());
loader.setController(this);
VBox root = loader.load();
backButton.setOnAction(e -> {
try {
backButtonPressed();
} catch (IOException ignored) {}
});
incorrectButton.setOnAction(e -> incorrect());
correctButton.setOnAction(e -> correct());
window.setTitle("Flashcard Application - Open Cards");
Scene mainMenuScene = new Scene(root, 1000, 750);
window.setScene(mainMenuScene);
int deckid = chooseCards();
String fileURL = "ftp://appuser:pass123.#127.0.0.1/decks/" + Integer.toString(deckid) + ".json";
URL url = new URL(fileURL); // Lines 43 to 45 come from https://www.javaworld.com/article/2073325/java-ftp-client-libraries-reviewed.html
URLConnection urlc = url.openConnection();
InputStream inputStream = urlc.getInputStream();
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(inputStream, "UTF-8"));
String title = (String) jsonObject.get("name");
titleLabel.setText(title);
}
I had to remove the attribute fx:controller="flashcardApplication.openCardsController from the FXML file and I had to replace the line Parent root = FXMLLoader.load(getClass().getResource("./mainPage.fxml")); with the following lines:
File file = new File(System.getProperty("user.dir") + "/src/flashcardApplication/openCardsPage.fxml");
FXMLLoader loader = new FXMLLoader(file.toURI().toURL());
loader.setController(this);
Please could someone explain why I had to use the different solution because I used the one line solution in two other FXML files and their corresponding controller classes without any issues
The #FXML-annotated fields are initialized in the controller when the FXML is loaded. By default, the FXMLLoader creates an instance of the class specified by the fx:controller attribute, and uses it as the controller.
Consequently, in your original code, the controller is not the current instance of OpenCardsController on which openCards() is being invoked, but is the new instance of the same class. Thus the #FXML-annotated fields are not initialized in the current instance, but in the new instance that is created by the FXMLLoader.
By removing the fx:controller attribute, and explicitly setting the controller to the exact object you need (the current instance of OpenCardsController), you achieve what you need: the controller is now the current instance and the FXML-annotated fields are initialized in that object.
Note that it's a bit unusual to load the FXML file from the controller itself. The typical approach is to load the FXML from some other code, and display the resulting UI; the controller is usually a separate object. It may be more natural (and easier to maintain in the long run) if you refactor your code so that the FXML is loaded from somewhere else. (This is really a separation of concerns and single-responsibility issue: the controller should only be responsible for processing user input from the corresponding FXML file; it should not be responsible for loading the FXML as well.)

Javafx TableView fails to show anything, but complies without error? [duplicate]

OK, new to java by several weeks, but have been programming for 30 years. The following code executes, but only the first column is showing anything. The data object is showing multiple rows of data, with fields of data that are filled in. I'm sure I'm missing something, and have looked through similar questions on here.
APVoucher_batchgridController.java
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author kmitchell
*/
public class APVoucher_batchgridController implements Initializable {
public TableView tblMainList;
public TableColumn colDateEntered;
public TableColumn colCreatedBy;
public TableColumn colDescription;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
public void opentables(ActionEvent event) {
Object forName = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("DateEntered"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("cDesc"));
colCreatedBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("CreatedBy"));
try {
// load the driver into memory
forName = Class.forName("jstels.jdbc.dbf.DBFDriver2");
} catch (ClassNotFoundException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conn = DriverManager.getConnection("jdbc:jstels:dbf:e:\\keystone-data\\keyfund\\seymour\\keyfund.dbc");
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (conn != null) {
try {
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (stmt != null) {
// execute a query
try {
ObservableList<Object> data = FXCollections.observableArrayList();
rs = stmt.executeQuery("SELECT denteredon, cdesc, ccreatedby FROM apvbatch WHERE ldeleted = false ORDER BY denteredon DESC");
while (rs.next()) {
String enteredon = rs.getString("denteredon");
String desc = rs.getString("cdesc");
String createdby = rs.getString("ccreatedby");
sresult row = new sresult(createdby, enteredon, desc);
data.add(row);
}
tblMainList.setItems(data);
tblMainList.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class sresult {
private String DateEntered;
private String EnteredBy;
private String cDesc;
public sresult(String T, String d, String c) {
this.EnteredBy = T;
this.DateEntered = d;
this.cDesc = c;
}
public String getEnteredBy() {
return EnteredBy;
}
public void setEnteredBy(String T) {
EnteredBy = T;
}
public String getDateEntered() {
return DateEntered;
}
public void setDateEntered(String d) {
DateEntered = d;
}
public String getcDesc() {
return cDesc;
}
public void setcDesc(String c) {
cDesc = c;
}
}
}
and APVoucher_batchgrid.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" fx:id="batchlistform" prefHeight="400.0" prefWidth="600.0" styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="keystone.APVoucher_batchgridController">
<children>
<BorderPane layoutX="0.0" layoutY="0.0" prefHeight="400.0" prefWidth="600.0">
<center>
<AnchorPane prefHeight="-1.0" prefWidth="-1.0">
<children>
<Pane layoutX="0.0" layoutY="0.0" prefHeight="53.0" prefWidth="580.0">
<children>
<Label layoutX="7.0" layoutY="9.0" prefWidth="202.0" text="AP Vouchers Batch List">
<font>
<Font name="System Bold" size="14.0" />
</font>
</Label>
<Button fx:id="btnClose" cancelButton="true" layoutX="513.0" layoutY="27.0" mnemonicParsing="false" text="Close" />
<Button id="btnClose" fx:id="apvRefresh" cancelButton="true" layoutX="185.0" layoutY="27.0" mnemonicParsing="false" onAction="#opentables" text="Refresh" />
</children>
</Pane>
<TableView fx:id="tblMainList" layoutX="0.0" layoutY="53.0" prefHeight="323.0" prefWidth="580.0">
<columns>
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="91.0" text="Date Entered" fx:id="colDateEntered" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="100.0" text="Created By" fx:id="colCreatedBy" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="261.0" text="Description" fx:id="colDescription" />
</columns>
</TableView>
</children>
</AnchorPane>
</center>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</BorderPane>
</children>
<stylesheets>
<URL value="#apvoucher_batchgrid.css" />
</stylesheets>
</AnchorPane>
THANK YOU for the answer. Way to many years in case insensitive languages. This has been a quick and dirty exercise for me to learn java and the latest & greatest stuff or as I like to say New Exciting Technology (NExT!)
For anyone looking at the answer and still not completely clued in, here are the changes that made the code work properly.
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("Denteredon"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("CDesc"));
colEnteredBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("Ccreatedby"));
public class sresult {
private String Denteredon;
private String Ccreatedby;
private String CDesc;
public sresult(String T, String d, String c) {
this.Ccreatedby = T;
this.Denteredon = d;
this.CDesc = c;
}
public String getCcreatedby() {
return Ccreatedby;
}
public void setCreatedby(String T) {
Ccreatedby = T;
}
public String getDenteredon() {
return Denteredon;
}
public void setDenteredon(String d) {
Denteredon = d;
}
public String getCDesc() {
return CDesc;
}
public void setCDesc(String c) {
CDesc = c;
}
}
}
This question is really a duplicate of: Javafx PropertyValueFactory not populating Tableview, but I'll specifically address your specific case, so it's clear.
Suggested solution (use a Lambda, not a PropertyValueFactory)
Instead of:
aColumn.setCellValueFactory(new PropertyValueFactory<Appointment,LocalDate>("date"));
Write:
aColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
For more information, see this answer:
Java: setCellValuefactory; Lambda vs. PropertyValueFactory; advantages/disadvantages
How do you use a JavaFX TableView with java records?
demonstrates replacing PropertyValueFactory with lambda expressions.
Solution using PropertyValueFactory
The lambda solution outlined above is preferred, but if you wish to use PropertyValueFactory, this alternate solution provides information on that.
Background
PropertyValueFactory uses reflection to determine the methods to get and set data values as well as to retrieve bindable properties from your model class. The pattern followed is:
PropertyValueType getName()
void setName(PropertyValueType value)
PropertyType nameProperty()
Where "name" is the string specified in the PropertyValueFactory constructor. The first letter of the property name in the getter and setter is capitalized (by java bean naming convention).
Why your application doesn't work
You have these three expressions:
new PropertyValueFactory<sresult, String>("DateEntered")
new PropertyValueFactory<sresult, String>("cDesc")
new PropertyValueFactory<sresult, String>("CreatedBy")
For your sample properties, the PropertyValueFactory will look for these methods:
"DateEntered" => getDateEntered()
"cDesc" => getCDesc()
"CreatedBy" => getCreatedBy()
And you have these three getters on your sresult class:
getDateEntered()
getcDesc()
getEnteredBy()
Only getDateEntered() is going to be picked up by the PropertyValueFactory because that is the only matching method defined in the sresult class.
Advice
You will have to adopt Java standards if you want the reflection in PropertyValueFactory to work (the alternative is to not use the PropertyValueFactory and instead write your own cell factories from scratch).
Adopting Java camel case naming conventions also makes it easier for Java developers to read your code.
Some times columns doesn't show data because of column names. eg,
new PropertyValueFactory<sresult, String>("cDesc")
and getter is getcDesc cDesc column may not display data. If you change code to
new PropertyValueFactory<sresult, String>("CDesc")
and getter is getCDesc CDesc column may display data.
For anyone else who still wasn't getting it after going through the above, my problem was that I wasn't specifying my setters with the "public final" designation.

Why I only get one column when using TableView with JavaFX? [duplicate]

OK, new to java by several weeks, but have been programming for 30 years. The following code executes, but only the first column is showing anything. The data object is showing multiple rows of data, with fields of data that are filled in. I'm sure I'm missing something, and have looked through similar questions on here.
APVoucher_batchgridController.java
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author kmitchell
*/
public class APVoucher_batchgridController implements Initializable {
public TableView tblMainList;
public TableColumn colDateEntered;
public TableColumn colCreatedBy;
public TableColumn colDescription;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
public void opentables(ActionEvent event) {
Object forName = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("DateEntered"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("cDesc"));
colCreatedBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("CreatedBy"));
try {
// load the driver into memory
forName = Class.forName("jstels.jdbc.dbf.DBFDriver2");
} catch (ClassNotFoundException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conn = DriverManager.getConnection("jdbc:jstels:dbf:e:\\keystone-data\\keyfund\\seymour\\keyfund.dbc");
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (conn != null) {
try {
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (stmt != null) {
// execute a query
try {
ObservableList<Object> data = FXCollections.observableArrayList();
rs = stmt.executeQuery("SELECT denteredon, cdesc, ccreatedby FROM apvbatch WHERE ldeleted = false ORDER BY denteredon DESC");
while (rs.next()) {
String enteredon = rs.getString("denteredon");
String desc = rs.getString("cdesc");
String createdby = rs.getString("ccreatedby");
sresult row = new sresult(createdby, enteredon, desc);
data.add(row);
}
tblMainList.setItems(data);
tblMainList.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class sresult {
private String DateEntered;
private String EnteredBy;
private String cDesc;
public sresult(String T, String d, String c) {
this.EnteredBy = T;
this.DateEntered = d;
this.cDesc = c;
}
public String getEnteredBy() {
return EnteredBy;
}
public void setEnteredBy(String T) {
EnteredBy = T;
}
public String getDateEntered() {
return DateEntered;
}
public void setDateEntered(String d) {
DateEntered = d;
}
public String getcDesc() {
return cDesc;
}
public void setcDesc(String c) {
cDesc = c;
}
}
}
and APVoucher_batchgrid.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" fx:id="batchlistform" prefHeight="400.0" prefWidth="600.0" styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="keystone.APVoucher_batchgridController">
<children>
<BorderPane layoutX="0.0" layoutY="0.0" prefHeight="400.0" prefWidth="600.0">
<center>
<AnchorPane prefHeight="-1.0" prefWidth="-1.0">
<children>
<Pane layoutX="0.0" layoutY="0.0" prefHeight="53.0" prefWidth="580.0">
<children>
<Label layoutX="7.0" layoutY="9.0" prefWidth="202.0" text="AP Vouchers Batch List">
<font>
<Font name="System Bold" size="14.0" />
</font>
</Label>
<Button fx:id="btnClose" cancelButton="true" layoutX="513.0" layoutY="27.0" mnemonicParsing="false" text="Close" />
<Button id="btnClose" fx:id="apvRefresh" cancelButton="true" layoutX="185.0" layoutY="27.0" mnemonicParsing="false" onAction="#opentables" text="Refresh" />
</children>
</Pane>
<TableView fx:id="tblMainList" layoutX="0.0" layoutY="53.0" prefHeight="323.0" prefWidth="580.0">
<columns>
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="91.0" text="Date Entered" fx:id="colDateEntered" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="100.0" text="Created By" fx:id="colCreatedBy" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="261.0" text="Description" fx:id="colDescription" />
</columns>
</TableView>
</children>
</AnchorPane>
</center>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</BorderPane>
</children>
<stylesheets>
<URL value="#apvoucher_batchgrid.css" />
</stylesheets>
</AnchorPane>
THANK YOU for the answer. Way to many years in case insensitive languages. This has been a quick and dirty exercise for me to learn java and the latest & greatest stuff or as I like to say New Exciting Technology (NExT!)
For anyone looking at the answer and still not completely clued in, here are the changes that made the code work properly.
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("Denteredon"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("CDesc"));
colEnteredBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("Ccreatedby"));
public class sresult {
private String Denteredon;
private String Ccreatedby;
private String CDesc;
public sresult(String T, String d, String c) {
this.Ccreatedby = T;
this.Denteredon = d;
this.CDesc = c;
}
public String getCcreatedby() {
return Ccreatedby;
}
public void setCreatedby(String T) {
Ccreatedby = T;
}
public String getDenteredon() {
return Denteredon;
}
public void setDenteredon(String d) {
Denteredon = d;
}
public String getCDesc() {
return CDesc;
}
public void setCDesc(String c) {
CDesc = c;
}
}
}
This question is really a duplicate of: Javafx PropertyValueFactory not populating Tableview, but I'll specifically address your specific case, so it's clear.
Suggested solution (use a Lambda, not a PropertyValueFactory)
Instead of:
aColumn.setCellValueFactory(new PropertyValueFactory<Appointment,LocalDate>("date"));
Write:
aColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
For more information, see this answer:
Java: setCellValuefactory; Lambda vs. PropertyValueFactory; advantages/disadvantages
How do you use a JavaFX TableView with java records?
demonstrates replacing PropertyValueFactory with lambda expressions.
Solution using PropertyValueFactory
The lambda solution outlined above is preferred, but if you wish to use PropertyValueFactory, this alternate solution provides information on that.
Background
PropertyValueFactory uses reflection to determine the methods to get and set data values as well as to retrieve bindable properties from your model class. The pattern followed is:
PropertyValueType getName()
void setName(PropertyValueType value)
PropertyType nameProperty()
Where "name" is the string specified in the PropertyValueFactory constructor. The first letter of the property name in the getter and setter is capitalized (by java bean naming convention).
Why your application doesn't work
You have these three expressions:
new PropertyValueFactory<sresult, String>("DateEntered")
new PropertyValueFactory<sresult, String>("cDesc")
new PropertyValueFactory<sresult, String>("CreatedBy")
For your sample properties, the PropertyValueFactory will look for these methods:
"DateEntered" => getDateEntered()
"cDesc" => getCDesc()
"CreatedBy" => getCreatedBy()
And you have these three getters on your sresult class:
getDateEntered()
getcDesc()
getEnteredBy()
Only getDateEntered() is going to be picked up by the PropertyValueFactory because that is the only matching method defined in the sresult class.
Advice
You will have to adopt Java standards if you want the reflection in PropertyValueFactory to work (the alternative is to not use the PropertyValueFactory and instead write your own cell factories from scratch).
Adopting Java camel case naming conventions also makes it easier for Java developers to read your code.
Some times columns doesn't show data because of column names. eg,
new PropertyValueFactory<sresult, String>("cDesc")
and getter is getcDesc cDesc column may not display data. If you change code to
new PropertyValueFactory<sresult, String>("CDesc")
and getter is getCDesc CDesc column may display data.
For anyone else who still wasn't getting it after going through the above, my problem was that I wasn't specifying my setters with the "public final" designation.

JavaFx: parent.lookup returns null

I use osgi+cdi and I have the following code:
Parent parent=null;
FXMLLoader fxmlLoader=getFxmlLoader();
try {
parent = (Parent)fxmlLoader.load(getFxmlStream("tasklist.fxml"));
} catch (IOException ex) {
Logger.getLogger(TestGoView.class.getName()).log(Level.SEVERE, null, ex);
}
ComboBox comboBox=(ComboBox) parent.lookup("#testComboBox");
if (comboBox==null){
System.out.println("COMBOBOX NULL");
}else{
System.out.println("COMBOBOX NOT NULL");
}
And I have the following tasklist.fxml
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="440.0" prefWidth="757.0" xmlns="http://javafx.com/javafx/8.0.60-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.techsenger.testgo.core.adm.task.list.TaskDirListController">
<children>
<HBox>
<children>
<ToolBar maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" nodeOrientation="RIGHT_TO_LEFT" HBox.hgrow="SOMETIMES">
<items>
<ComboBox fx:id="testComboBox" maxWidth="1.7976931348623157E308" nodeOrientation="LEFT_TO_RIGHT" />
</items>
</ToolBar>
</children>
</HBox>
</children>
</VBox>
However parent.lookup("#testComboBox") returns null. How to explain it? I've checked the name of ID several times.
Instead of using a lookup, which will only work after the scene has been rendered, you can put the logic you need in your controller class. You can inject elements from the FXML file into the controller class by annotating them #FXML.
public class TaskDirListController {
#FXML
private ComboBox<...> testComboBox ;
public void initialize() {
System.out.println(testComboBox);
}
// ...
}
Lookups are generally not robust, and I would recommend avoiding using them. If you really need to access something defined in the FXML file from a class other than the controller, the first thing to do is to consider reorganizing things so that you don't need to do this: it really indicates that your overall design is wrong.
If you really need this for some reason, it's better to use the FXMLLoader's namespace than a lookup:
Parent parent=null;
FXMLLoader fxmlLoader=getFxmlLoader();
try {
parent = (Parent)fxmlLoader.load(getFxmlStream("tasklist.fxml"));
ComboBox<?> comboBox = (ComboBox<?>) fxmlLoader.getNamespace().get("testComboBox");
System.out.println(comboBox);
} catch (IOException ex) {
Logger.getLogger(TestGoView.class.getName()).log(Level.SEVERE, null, ex);
}
It is because you are trying to use lookup before showing the parent on the screen.
Pane root = FXMLLoader.load(getClass().getResource("tasklist.fxml"));
System.out.println(root.lookup("#testComboBox")); //returns null
primaryStage.setScene(new Scene(root));
primaryStage.show();
System.out.println(root.lookup("#testComboBox")); //returns
// ComboBox[id=testComboBox, styleClass=combo-box-base combo-box]

Categories

Resources