How to access objects from event listener in javafx - javafx

I have an object Contract and it contains Summary and Observable List of another object ContractDetails inside it.
Now, I am using ContractDetails to populate in tableview from Contract object.
I have a save button, which on clicking needs to save Contract along with ContractDetails. I am able to access ContractDetails since they are in tableview.
How do I access Contract properties in eventlistener of save button.
The related code is given below
public class Contract {
private String tradeDate;
private String contractNote;
.....
.....
private String brokerId;
private ObservableList<ContractDetails> contractdetails = FXCollections.observableArrayList();
public Contract() {
}
public Contract(String tradeDate, String contractNote, ....., String brokerId,ObservableList<ContractDetails> contractdetails) {
this.tradeDate = tradeDate;
this.contractNote = contractNote;
....
....
this.contractdetails=contractdetails;
}
public String getTradeDate() {
return tradeDate;
}
public void setTradeDate(String tradeDate) {
this.tradeDate = tradeDate;
}
public String getContractNote() {
return contractNote;
}
public void setContractNote(String contractNote) {
this.contractNote = contractNote;
}
....
....
public ObservableList<ContractDetails> getContractdetails() {
return contractdetails;
}
public void setContractdetails(ObservableList<ContractDetails> contractdetails) {
this.contractdetails = contractdetails;
}
}
public class ContractDetails {
private String orderNo;
private String contractType;
private String symbol;
private String buysell;
private Integer quantity;
private Double buysellprice;
private Double netcontractValue;
public ContractDetails() {
}
public ContractDetails(String orderNo, String contractType, String symbol, String buysell, Integer quantity, Double buysellprice, Double netcontractValue) {
this.orderNo = orderNo;
this.symbol = symbol;
this.buysell = buysell;
this.quantity = quantity;
this.buysellprice = buysellprice;
this.netcontractValue = netcontractValue;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
....
....
public Double getNetcontractValue() {
return netcontractValue;
}
public void setNetcontractValue(Double netcontractValue) {
this.netcontractValue = netcontractValue;
}
}
In the controller
==================
public class ContractViewController implements Initializable {
#FXML
private TableView<ContractDetails> tblcontractfx;
#FXML
private TableColumn<ContractDetails, String> contractTypefx;
#FXML
private TableColumn<ContractDetails, String> symbolfx;
....
....
#FXML
private Button savefx;
#FXML
private TextField txtclientcodefx;
#FXML
private TextField txttradedtfx;
private void fetchContracts(TableView tableView, Contract contract)
{ txttradedtfx.setText(contract.getTradeDate());
txtclientcodefx.setText(contract.getClientCode());
symbolfx.setCellValueFactory(new PropertyValueFactory<ContractDetails, String>("symbol"));
contractTypefx.setCellValueFactory(new PropertyValueFactory<ContractDetails, String>("contractType"));
tableView.setItems((ObservableList) contract.getContractdetails());
#FXML
private void saveClicked(ActionEvent event) { DBConnection DBcon = new DBConnection();
//Now I am getting the contract details from tableview tblcontractfx
ObservableList<ContractDetails> contractdetails = tblcontractfx.getItems();
//How do I get the summary values from contract. I am able to get those which are in text fields like txttradedtfx and txtclientcodefx.However contractNote which I am not using, I still need to retrieve it to populate into database.
String clientCode=txtclientcodefx.getText();
Thanks

Just store the contract in a local variable.
Contract contract;
private void fetchContracts(TableView tableView, Contract contract)
{
this.contract = contract;
...
}
private void saveClicked(ActionEvent event) {
// here you have full access to the contract variable
String contractNote = contract.getContractNote();
}
As an alternative, if you insist on combining it all in a single table, you could put the Contract into the table via setUserData and retrieve it via getUserData.
By the way, I still don't get your code. Why is there a tableView parameter when you have full access to TableView<ContractDetails> tblcontractfx

Related

JavaFX Application fails to compile on lambda expression

I am trying to build a JavaFX Application to display a TreeTableView. Still setting up this whole thing. I got it to work with only one column without the Product class but i am struggling to make it work with the Product class and two columns. The following piece of code fails to compile:
col1.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<Product, String> param) -> param.getValue().getValue().getNameProperty());
and spits out this error:
Error:(38, 121) java: incompatible types: bad return type in lambda expression
java.lang.String cannot be converted to javafx.beans.value.ObservableValue<java.lang.String>
This is the entire code:
public class Controller implements Initializable {
#FXML
private TreeTableView<Product> tableView;
#FXML
private TreeTableColumn<Product, String> col1;
#FXML
private TreeTableColumn<Product, String> col2;
TreeItem<Product> product1 = new TreeItem<>(new Product("Bread", "300g"));
TreeItem<Product> product2 = new TreeItem<>(new Product("Eggs", "5"));
TreeItem<Product> product3 = new TreeItem<>(new Product("Brad Pitt", "One and Only one"));
TreeItem<Product> product4 = new TreeItem<>(new Product("Moisturizer", "20"));
TreeItem<Product> product5 = new TreeItem<>(new Product("Horse Lubricant", "4"));
TreeItem<Product> root = new TreeItem<>(new Product("Name", "Quantity"));
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
root.getChildren().setAll(product1, product2, product3, product4, product5);
col1.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<Product, String> param) -> param.getValue().getValue().getNameProperty());
col2.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<Product, String> param) -> param.getValue().getValue().getQuantityProperty());
tableView.setRoot(root);
tableView.setShowRoot(false);
}
public class Product{
SimpleStringProperty nameProperty;
SimpleStringProperty quantityProperty;
public Product(String name, String quantity){
this.nameProperty = new SimpleStringProperty(name);
this.quantityProperty = new SimpleStringProperty(quantity);
}
public String getNameProperty() {
return nameProperty.get();
}
public SimpleStringProperty namePropertyProperty() {
return nameProperty;
}
public void setNameProperty(String nameProperty) {
this.nameProperty.set(nameProperty);
}
public String getQuantityProperty() {
return quantityProperty.get();
}
public SimpleStringProperty quantityPropertyProperty() {
return quantityProperty;
}
public void setQuantityProperty(String quantityProperty) {
this.quantityProperty.set(quantityProperty);
}
}
}
First, your Product class is not conventional. Typically the field name matches the property name (e.g. name, not nameProperty). Then you name your getter, setter, and property getter after the name of the property. For instance:
import javafx.beans.property.StringProperty;
import javafx.beans.property.SimpleStringProperty;
public class Product {
private final StringProperty name = new SimpleStringProperty(this, "name");
public final void setName(String name) { this.name.set(name); }
public final String getName() { return name.get(); }
public final StringProperty nameProperty() { return name; }
private final StringProperty quantity = new SimpleStringProperty(this, "quantity");
public final void setQuantity(String quantity) { this.quantity.set(quantity); }
public final String getQuantity() { return quantity.get(); }
public final StringProperty quantityProperty() { return quantity; }
public Product() {} // typically Java(FX)Beans provide no-arg constructors as well
public Product(String name, String quantity) {
setName(name);
setQuantity(quantity);
}
}
Note: Your class is a non-static nested (i.e. inner) class. This means each Product instance requires an instance of the enclosing class. If you want to keep Product a nested class, consider making it static. My example above assumes Product is in its own source file.
With that class, you would define your cell value factories like so:
TreeTableColumn<Product, String> nameCol = ...;
nameCol.setCellValueFactory(data -> data.getValue().getValue().nameProperty());
TreeTableColumn<Product, String> quantityCol = ...;
quantityCol.setCellValueFactory(data -> data.getValue().getValue().quantityProperty());
Notice the factories return the appropriate property of the Product instance. This solves your compilation error since StringProperty is an instance of ObservableValue<String>. It also means your table has direct access to the backing model's property, which helps with keeping the table up-to-date and also with implementing inline editing.
In case it helps, here's setting the cell value factory of nameCol using an anonymous class which explicitly shows all the types used:
nameCol.setCellValueFactory(new Callback<>() { // may have to explicitly define type arguments, depending on version of Java
#Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Product, String> data) {
TreeItem<Product> treeItem = data.getValue();
Product product = treeItem.getValue();
return product.nameProperty();
}
});

How to build JavaFX styleable objects properly, that can be GC

I decided to refactor my application because of hugh memory leaks in the old version. For visualization objects, I decide to not more using fxml, but Styleable interface.
So I created a class Sim Photo like this :
public class SimPhoto extends Control {
private static final String DEFAULT_CLASS_NAME = "sim-photo";
private static final Double DEFAULT_STROKE_WIDTH = 0.0;
#Getter
#Setter
private static String DEFAULT_PHOTO = "";
private StyleableStringProperty imgPath;
private StyleableIntegerProperty arcHeight;
private StyleableIntegerProperty arcWidth;
private DoubleProperty strokeWidth;
private ObjectProperty<Paint> stroke;
private ObjectProperty<Paint> fill;
public SimPhoto() {
initialize();
}
public SimPhoto(#NamedArg("imgPath") String imgPath) {
this();
this.imgPathProperty().set(imgPath);
}
//Example of init properties
public final StyleableIntegerProperty arcHeightProperty() {
if (arcHeight == null) {
arcHeight = new SimpleStyleableIntegerProperty(
StyleableProperties.ARC_WIDTH,
SimPhoto.this,
"arcWidth",
0
);
}
return arcHeight;
}
public final StringProperty imgPathProperty() {
if(imgPath == null) {
imgPath = new SimpleStyleableStringProperty(
StyleableProperties.IMG_PATH,
SimPhoto.this,
"imgPath",
"");
}
return imgPath;
}
(...)
}
In my skin class, I use binding of properties from Control Class
public class SimPhotoSkin extends SkinBase<SimPhoto> {
#Getter
private Rectangle photoFond = new Rectangle();
private Rectangle photoView = new Rectangle();
private boolean invalidate = false;
private InvalidationListener invalidListener = this::invalidated;
private ChangeListener<String> pathListener = this::pathChanged;
public SimPhotoSkin(SimPhoto control) {
super(control);
initVisualization();
initListeners();
}
private void initVisualization() {
getChildren().addAll(photoFond, photoView);
if (getSkinnable().imgPathProperty() != null) {
setNewFond(getSkinnable().getImgPath());
}
}
private void initListeners() {
photoFond.widthProperty().bind(getSkinnable().widthProperty().subtract(5));
photoFond.heightProperty().bind(getSkinnable().heightProperty().subtract(5));
photoView.widthProperty().bind(photoFond.widthProperty().subtract(photoFond.strokeWidthProperty()));
photoView.heightProperty().bind(photoFond.heightProperty().subtract(photoFond.strokeWidthProperty()));
photoView.arcWidthProperty().bind(getSkinnable().arcWidthProperty());
photoView.arcHeightProperty().bind(getSkinnable().arcHeightProperty());
photoFond.arcWidthProperty().bind(getSkinnable().arcWidthProperty());
photoFond.arcHeightProperty().bind(getSkinnable().arcHeightProperty());
photoFond.fillProperty().bind(getSkinnable().fillProperty());
photoFond.strokeProperty().bind(getSkinnable().strokeProperty());
photoFond.strokeWidthProperty().bind(getSkinnable().strokeWidthProperty());
getSkinnable().imgPathProperty().addListener(pathListener);
}
private void pathChanged(ObservableValue<? extends String> observable, String oldValue, String newValue) {
(...)
}
private void setNewFond(String path) {
(...)
}
private void invalidated(Observable observable) {
invalidate = true;
}
}
I know that object cannot been GC while exist a reference to it. So I have a big problem, because event these objects are no more used, thay cannot be GC , and in my application ,when I need creating more than 300 objects at time is a big problem.
I tried to create method clean(), that will be unbind all bidnings and listeners, but it's not realy helpful. Problem still persist.
I'm thinking about any workaround like a Manager, that will store all objects in queue and while calling will return one objects disponibles or create new one.
But this is the last possibility, if I dont find any solution for my problem, and I would like avoid this.

In javafx table view doesn't display

//Database is Sucessfully Connected
I am trying to Create a table in which I want to display the contents of my 'student' table in tableView of Javafx but I could not get the desired output.
ObservableList<Student> list = FXCollections.observableArrayList();
#FXML
//Initializes the controller class.
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO
initCol();
loadTable();
}
//A view Table has been made with fx:id-table
//Variable name for 2 columns are 'fx:id-rollnoColand' & 'fx:id-nameCol'
#FXML
private TableView<Student> table;
#FXML
private TableColumn<Student,String> rollnoCol;
#FXML
private TableColumn<Student,String> nameCol;
private void initCol()
{
rollnoCol.setCellValueFactory(new PropertyValueFactory<>("s_rollno"));
nameCol.setCellValueFactory(new PropertyValueFactory<>("s_name"));
}
//Name of the Table is 'student' with Columns 'rollno' and 'name'
private void loadTable()
{
String selectAll = "select * from student";
try
{
Statement stmt = connectdb.createStatement();
ResultSet rs = stmt.executeQuery(selectAll);
while(rs.next())
{
String getrollno = rs.getString("rollno");
String getname = rs.getString("name");
list.add(new Student(getrollno,getname));
}
}
catch(SQLException exp)
{
System.out.println(exp);
}
table.getItems().setAll(list);
}
public static class Student
{
private final String s_rollno;
private final String s_name;
Student(String rollno,String name)
{
this.s_rollno = rollno;
this.s_name = name;
}
}
PropertyValueFactory works with getters or property methods. In your case you need to add getters for your properties in the Student class to enable PropertyValueFactory to retrieve the values:
public static class Student {
private final String s_rollno;
private final String s_name;
Student(String rollno, String name) {
this.s_rollno = rollno;
this.s_name = name;
}
public String getS_rollno() {
return s_rollno;
}
public String getS_name() {
return s_name;
}
}
I had this problem before,and it has many reason.First ,you may remove final keyword from your model,because your variables are changing.Second, TableView shows empty cells because you make your variables private in class Student and you can not access them from init method in parent class.So you need add getter and setter methods for access to these variables.
public static class Student
{
private String s_rollno;
private String s_name;
Student(String rollno,String name)
{
this.s_rollno = rollno;
this.s_name = name;
}
public String getS_rollno() {
return s_rollno;
}
public void setS_rollno(String s_rollno) {
this.s_rollno = s_rollno;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
}

JavaFX: TableView(fxml) filling with data

either i am looking at it for to long... or i did not really understand it.
In any case i am trying to fill a tableview that has been created using fxml (inc. Columns) with data.
My Code works for the first (Title) column but not for the rest.
(Yes "data" has all the info in it... checked with debug.)
So can any1 tell me what i am doing wrong??
Here (hopefully all relevant) code (copied together):
#FXML private TableColumn<sresult,String> cl_title;
#FXML private TableColumn<sresult, String> cl_url;
#FXML private TableColumn<sresult, String> cl_poster;
#FXML private TableColumn<sresult, String> cl_date;
#FXML private TableColumn<sresult, String> cl_forum;
String[][] search_res=null;
try {
search_res= search(tf_search.getText());
} catch (MalformedURLException | SolrServerException | ParseException ex) {
Logger.getLogger(MainUiController.class.getName()).log(Level.SEVERE, null, ex);
}
final ObservableList<sresult> data= FXCollections.observableArrayList();
for ( String[] s : search_res){
data.add(new sresult(s[0], s[2],s[3],s[4],s[1]));
}
cl_title.setCellValueFactory(
new PropertyValueFactory<sresult,String>("Title"));
cl_poster.setCellValueFactory(
new PropertyValueFactory<sresult,String>("poster"));
cl_date.setCellValueFactory(
new PropertyValueFactory<sresult,String>("date"));
cl_forum.setCellValueFactory(
new PropertyValueFactory<sresult,String>("forum"));
cl_url.setCellValueFactory(
new PropertyValueFactory<sresult,String>("link"));
tb_results.setItems(data);
public class sresult {
private final SimpleStringProperty Title;
private final SimpleStringProperty poster;
private final SimpleStringProperty date;
private final SimpleStringProperty forum;
private final SimpleStringProperty link;
public sresult(String T, String p, String d, String f, String l) {
this.Title = new SimpleStringProperty(T);
this.poster = new SimpleStringProperty(p);
this.date = new SimpleStringProperty(d);
this.forum = new SimpleStringProperty(f);
this.link = new SimpleStringProperty(l);
}
public String getTitle() {
return Title.get();
}
public void setTitle(String T) {
Title.set(T);
}
public String getposter() {
return poster.get();
}
public void setposter(String p) {
poster.set(p);
}
public String getdate() {
return date.get();
}
public void setdate(String d) {
date.set(d);
}
public String getforum() {
return forum.get();
}
public void setforum(String f) {
forum.set(f);
}
public String getlink() {
return link.get();
}
public void setlink(String l) {
link.set(l);
}
}
Thank you!
Ok,
This was simular enough for me to get the answer.
The getter and setters need to have a Capital letter after get/set.
e.g. public String getTitle() vs public String gettitle()
not really sure why java is forcing this...
Anyway thanks to jewelsea for his answer on the other question.

Google App Engine Datanucleus enhencer

I have following class as superclass
#Entity
#MappedSuperclass
public class Location implements LocationCapable {
#Basic
private Double latitude;
#Basic
private Double longitude;
#Basic
private List<String> geocells;
#PrePersist
#Transient
private void generateGeoCells() {
geocells = GeocellManager.generateGeoCell(getLocation());
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
#Override
#Transient
#JsonIgnore
public Point getLocation() {
return new Point(latitude, longitude);
}
#Override
#Transient
#JsonIgnore
public String getKeyString() {
return latitude + ":" + longitude;
}
#Override
public List<String> getGeocells() {
return geocells;
}
public void setGeocells(List<String> geocells) {
this.geocells = geocells;
}
}
And another one which inherits from this
But when I try to run JUnit test I got this
Caused by: org.datanucleus.metadata.InvalidMetaDataException: Class Location has application-identity and no objectid-class specified yet has 0 primary key fields. Unable to use SingleFieldIdentity.
at org.datanucleus.metadata.AbstractClassMetaData.determineObjectIdClass(AbstractClassMetaData.java:1032)
at org.datanucleus.metadata.ClassMetaData.populate(ClassMetaData.java:205)
at org.datanucleus.metadata.AbstractClassMetaData.validateSuperClass(AbstractClassMetaData.java:720)
at org.datanucleus.metadata.AbstractClassMetaData.determineSuperClassName(AbstractClassMetaData.java:642)
at org.datanucleus.metadata.ClassMetaData.populate(ClassMetaData.java:193)
at org.datanucleus.metadata.MetaDataManager$1.run(MetaDataManager.java:2317)
at java.security.AccessController.doPrivileged(Native Method)
at org.datanucleus.metadata.MetaDataManager.populateAbstractClassMetaData(MetaDataManager.java:2311)
at org.datanucleus.metadata.MetaDataManager.populateFileMetaData(MetaDataManager.java:2148)
at org.datanucleus.metadata.MetaDataManager.initialiseFileMetaDataForUse(MetaDataManager.java:864)
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:794)
at org.datanucleus.jpa.EntityManagerFactoryImpl.initialisePMF(EntityManagerFactoryImpl.java:488)
at org.datanucleus.jpa.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:355)
at org.datanucleus.store.appengine.jpa.DatastoreEntityManagerFactory.<init>(DatastoreEntityManagerFactory.java:63)
at org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider.createEntityManagerFactory(DatastorePersistenceProvider.java:35)
at javax.persistence.Persistence.createFactory(Persistence.java:172)
... 67 more
Also I've tried to add in supperclass the key field annotated with #Id but it gives no result for me
You have to have an #Id field, as the message says.
Looks like it was some problem with enhancing or eclipse plugin, no metter after restart of IDE the problem dessapiared. But only this problem with ID. Actually I've faced with another very strange problem related to embedded entities. I have following domain model:
#Entity
public class City {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key id;
#Basic
private String name;
// Entity won't persist if location is not null, requires to persist with
// further update
#Embedded
// #OneToOne(cascade = CascadeType.ALL) it works the same when I add or remove this line
private Location location;
/* getters and setters */
}
#Embeddable
public class Location implements LocationCapable {
#Basic
#NotNull
private Double latitude;
#Basic
#NotNull
private Double longitude;
#Basic
private List<String> geocells;
/* getters and setters */
}
To test it I have following JUnit test case:
#Test
public void testSave() throws Exception {
City city = new City("testCity1", new Location(1d, 1d));
cityDao.persist(city);
assertNotNull(city.getId());
}
cityDao.persist(city) does simply jpaTemplate.persist(object);
And at when I try to persist this entity I got following exception:
Caused by: java.lang.IllegalArgumentException: out of field index :-1
at com.myproject.model.Location.jdoProvideField(Location.java)
at org.datanucleus.state.JDOStateManagerImpl.provideField(JDOStateManagerImpl.java:2585)
at org.datanucleus.state.JDOStateManagerImpl.provideField(JDOStateManagerImpl.java:2555)
at org.datanucleus.store.mapped.mapping.CollectionMapping.postInsert(CollectionMapping.java:91)
at org.datanucleus.store.mapped.mapping.EmbeddedPCMapping.postInsert(EmbeddedPCMapping.java:104)
at org.datanucleus.store.appengine.DatastoreRelationFieldManager.runPostInsertMappingCallbacks(DatastoreRelationFieldManager.java:217)
at org.datanucleus.store.appengine.DatastoreRelationFieldManager.access$200(DatastoreRelationFieldManager.java:48)
at org.datanucleus.store.appengine.DatastoreRelationFieldManager$1.apply(DatastoreRelationFieldManager.java:116)
at org.datanucleus.store.appengine.DatastoreRelationFieldManager.storeRelations(DatastoreRelationFieldManager.java:81)
at org.datanucleus.store.appengine.DatastoreFieldManager.storeRelations(DatastoreFieldManager.java:955)
at org.datanucleus.store.appengine.DatastorePersistenceHandler.storeRelations(DatastorePersistenceHandler.java:546)
at org.datanucleus.store.appengine.DatastorePersistenceHandler.insertPostProcess(DatastorePersistenceHandler.java:304)
at org.datanucleus.store.appengine.DatastorePersistenceHandler.insertObjects(DatastorePersistenceHandler.java:256)
at org.datanucleus.store.appengine.DatastorePersistenceHandler.insertObject(DatastorePersistenceHandler.java:240)
at org.datanucleus.state.JDOStateManagerImpl.internalMakePersistent(JDOStateManagerImpl.java:3185)
at org.datanucleus.state.JDOStateManagerImpl.flush(JDOStateManagerImpl.java:4513)
at org.datanucleus.ObjectManagerImpl.flushInternal(ObjectManagerImpl.java:2814)
at org.datanucleus.ObjectManagerImpl.flush(ObjectManagerImpl.java:2754)
at org.datanucleus.ObjectManagerImpl.preCommit(ObjectManagerImpl.java:2893)
at org.datanucleus.TransactionImpl.internalPreCommit(TransactionImpl.java:369)
at org.datanucleus.TransactionImpl.commit(TransactionImpl.java:256)
at org.datanucleus.jpa.EntityTransactionImpl.commit(EntityTransactionImpl.java:104)
at org.datanucleus.store.appengine.jpa.DatastoreEntityTransactionImpl.commit(DatastoreEntityTransactionImpl.java:55)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:467)
... 41 more

Resources