//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;
}
}
Related
In the JavaFx ComboBox which uses a class object list .I want to select items in the ComboBox programmatically using getSelectionModel().select(object or index). i am not getting the desired result Although the value is set but it is something like this main.dao.Company.Company.CompanyTableData#74541e7b.
The code is somewhat like this.
ComboBox<CompanyTableData> company = new ComboBox<>();
company.setItems(GetCompany.getCompanyTableData());//where Observable list is set..
GetCompany.getCompanyTableData() returns observablelist of CompanyTableData class.
The ComboBox Looks as follows.
The CompanyTableData Class is as.
public class CompanyTableData {
private SimpleStringProperty itemCompanyId;
private SimpleStringProperty itemCompanyName;
private SimpleStringProperty createBy;
private SimpleStringProperty createdOn;
public CompanyTableData(CompanyData companyData){
this.itemCompanyId = new SimpleStringProperty(companyData.getItemCompanyId());
this.itemCompanyName = new SimpleStringProperty(companyData.getItemCompanyName());
this.createBy = new SimpleStringProperty(companyData.getCreatedBy());
this.createdOn = new SimpleStringProperty(companyData.getCreatedOn());
}
public String getItemCompanyId() {
return itemCompanyId.get();
}
public SimpleStringProperty itemCompanyIdProperty() {
return itemCompanyId;
}
public void setItemCompanyId(String itemCompanyId) {
this.itemCompanyId.set(itemCompanyId);
}
public String getItemCompanyName() {
return itemCompanyName.get();
}
public SimpleStringProperty itemCompanyNameProperty() {
return itemCompanyName;
}
public void setItemCompanyName(String itemCompanyName) {
this.itemCompanyName.set(itemCompanyName);
}
public String getCreateBy() {
return createBy.get();
}
public SimpleStringProperty createByProperty() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy.set(createBy);
}
public String getCreatedOn() {
return createdOn.get();
}
public SimpleStringProperty createdOnProperty() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn.set(createdOn);
}
}
The Cell Factory is set
company.setCellFactory(param -> new CompanyCell());
And the CompanyCell
public class CompanyCell extends ListCell<CompanyTableData> {
#Override
protected void updateItem(CompanyTableData item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item.getItemCompanyName() == null) {
setText(null);
} else {
setText(item.getItemCompanyName());
}
}
}
After all this when i try to set the items programmetically as
company.getSelectionModel().select(getSelectedCompanyIndex());
The getSelectedCompanyIndex() function is as follows.
public static CompanyTableData getSelectedCompanyIndex(){
CompanyTableData c = null,i;
Iterator<CompanyTableData> itr = GetCompany.getCompanyTableData().iterator();
while (itr.hasNext()){
i = itr.next();
if (i.getItemCompanyName().equals(Element.getItemTableData().getCompany())){
c = i;
}
}
return c;
}
And the result i am getting is
And
At the end it should select a name or item in the list but it has set some type of object i think.
Now what should i do. Is there any type of string conversion required.
The buttonCell used to display the item when the combobox popup is not shown is not automatically created using the cellFactory. You need to set this property too to use the same cell implementation:
company.setCellFactory(param -> new CompanyCell());
company.setButtonCell(new CompanyCell());
I need to order the list of items based on a field say starredAt
I am loading the data in the recyclerview from Realm DB using RealmRecyclerView by thorbenprimke
The field changes it value on user's action i.e when user presses star button the item should be moved to top.
For this I am just updating the starredAt field of the object.
The items are already sorted by starredAt so realm loads the updated list but it randomly adds one more item to the recyclerview.
CheatSheet.java
public class CheatSheet extends RealmObject {
#PrimaryKey
private String id;
private RealmList<Item> items;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public RealmList<Item> getItems() {
return items;
}
public void setItems(RealmList<Item> items) {
this.items = items;
}
}
Item.java
public class Item extends RealmObject {
#PrimaryKey
private String id;
private String description;
private Date starredAt;
public Item() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getStarredAt() {
return starredAt;
}
public void setStarredAt(Date starredAt) {
this.starredAt = starredAt;
}
}
CheatSheetActivity.java
public class MainActivity extends AppCompatActivity {
RealmRecyclerView revItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setData();
}
private void setData() {
rvItems = (RealmRecyclerView) findViewById(R.id.rev_items);
RealmResults<Item> items = Realm.getDefaultInstance().where(CheatSheet.class)
.equalTo("id", "some-id").findFirst().getItems()
.where()
.findAllSorted("starredAt", Sort.DESCENDING);
ItemRealmListAdapter itemRealmListAdapter =
new ItemRealmListAdapter(this, items,
true, true);
rvItems.setAdapter(itemRealmListAdapter);
}
ItemRealmListAdapter.java
public class ItemRealmListAdapter extends RealmBasedRecyclerViewAdapter<Item,
ItemRealmListAdapter.ItemViewHolder> {
RealmResults<Item> mItems;
public ItemRealmListAdapter(Context context, RealmResults<Item> realmResults,
boolean automaticUpdate, boolean animateResults) {
super(context, realmResults, automaticUpdate, animateResults);
this.mItems = realmResults;
}
#Override
public ItemViewHolder onCreateRealmViewHolder(ViewGroup viewGroup, int i) {
return new ItemViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_layout_cs_text, viewGroup, false));
}
public Item getItem(int position) {
return mItems.get(position);
}
#Override
public void onBindRealmViewHolder(ItemViewHolder itemViewHolder, int position) {
itemViewHolder.txtBody.setText(getItem(position).getDescription());
if (getItem(position).getStarredAt() != null) {
itemViewHolder.imvStar.setImageResource(R.drawable.ic_star_yellow);
}
itemViewHolder.imvStar.setOnClickListener(v -> handleStarClick(v,position));
}
private void handleStarClick(View v, int position) {
if (getItem(position).getStarredAt() != null) {
((ImageView) v).setImageResource(R.drawable.ic_star);
CheatSheetStorage.unStarItem("some-id", getItem(position));
} else {
((ImageView) v).setImageResource(R.drawable.ic_star_yellow);
CheatSheetStorage.starItem("some-id", getItem(position));
}
}
public static class ItemViewHolder extends RealmViewHolder {
#Bind(R.id.txt_cheat_sheet)
TextView txtBody;
#Bind(R.id.img_star)
ImageView imvStar;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
CheatSheetStorage.java
public class CheatSheetStorage {
public static void unStarItem(String cheatSheetId, Item item) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CheatSheet cheatSheet = getCheatSheetById(cheatSheetId);
Item itemDB = cheatSheet.getItems().where().equalTo("id", item.getId()).findFirst();
itemDB.setStarredAt(null);
realm.commitTransaction();
}
public static void starItem(String cheatSheetId, Item item) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CheatSheet cheatSheet = getCheatSheetById(cheatSheetId);
Item itemDB = cheatSheet.getItems().where().equalTo("id", item.getId()).findFirst();
itemDB.setStarredAt(new Date());
realm.commitTransaction();
}
}
Please refer following screenshots for clearer idea :
Screenshot before starring
Screenshot after starring the sixth item
#Rohan-Peshkar - You will have to provide a animateExtraColumnName value to the adapter. For the animations, the adapter keeps track of the items and since that item's id doesn't change, the list isn't updated. With an additional column (in your case that should be the starredAt column - as long as it is stored as an Integer), the diffing algorithm will detect a change and the order is updated.
For reference: https://github.com/thorbenprimke/realm-recyclerview/blob/2835a543dce20993d8f98a4f773fa0e67132ce52/library/src/main/java/io/realm/RealmBasedRecyclerViewAdapter.java#L177
You can also check out the MainActivity in the example folder. The example changes a row's text from "ABC" to "Updated ABC" and the list recognizes the change because both the primary key and the quote field are used to basically create a composite key for diffing purposes.
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
I have tables with editable fields item,Description,Quantity,Unit price and Sub Total.
I am creating a cellFactory and Column Update like this:
TableColumn DescriptionCol = new TableColumn("Description");
EditableTableSupport.createEditingColumn(DescriptionCol,"description");
TableColumn QuantityCol = new TableColumn("Quantity");
EditableTableSupport.createEditingColumn(QuantityCol,"quantity");
TableColumn UnitPriceColumn = new TableColumn<>("Unit Price");
EditableTableSupport.createEditingColumn(UnitPriceColumn,"unitPrice");
TableColumn DiscountColumn = new TableColumn<>("Discount");
EditableTableSupport.createEditingColumn(DiscountColumn,"discount");
SubTotalColumn = new TableColumn<>("SubTotal");
EditableTableSupport.createColumn(SubTotalColumn,"subTotal");
TableColumn SubTotalColumn = new TableColumn<>("SubTotal");
EditableTableSupport.createColumn(SubTotalColumn,"subTotal");
DescriptionCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setDescription(t.getNewValue());
}
});
QuantityCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setQuantity(t.getNewValue());
}
});
UnitPriceColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setUnitPrice(t.getNewValue());
}
});
DiscountColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setDiscount(t.getNewValue());
}
});
public class EditableTableSupport {
public static void createEditingColumn(TableColumn Column ,String name){
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
Column.setSortable(false);
Column.setCellValueFactory(new PropertyValueFactory<DUMMY_PurchaseOrderLine, String>(name));
Column.setCellFactory(cellFactory);
}
public static void createColumn(TableColumn Column, String name) {
Column.setSortable(false);
Column.setCellValueFactory(new PropertyValueFactory<DUMMY_PurchaseOrderLine, String>(name));
}}
Question:How to Update Subtotal Column When i updating Quantity Column or UnitPrice Column
Thank you..
public class DUMMY_PurchaseOrderLine {
private String name;
private String description;
private BigDecimal quantity;
private BigDecimal unitPrice;
private BigDecimal discount;
private BigDecimal subTotal;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}
public BigDecimal getDiscount() {
return discount;
}
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
public BigDecimal getSubTotal() {
return subTotal;
}
public void setSubTotal(BigDecimal subTotal) {
this.subTotal = subTotal;
}
public DUMMY_PurchaseOrderLine(String name, BigDecimal description, BigDecimal quantity,BigDecimal unitPrice,BigDecimal discount,BigDecimal subTotal) {
this.name = name;
this.description = description;
this.quantity = quantity;
this.unitPrice = unitPrice;
this.discount = discount;
this.subTotal = quantity.multiply(unitPrice).subtract(discount);
}
}
In your DUMMY_PurchaseOrderLine class create a read only property named subTotal and initialize it in the constructor via binding. The combination of the binding and the PropertyValueFactory you use to set the value for the SubTotalColumn will ensure that the correct subtotal is always reflected.
class DUMMY_PurchaseOrderLine {
private IntegerProperty quantity = new SimpleIntegerProperty(0);
private DoubleProperty unitPrice = new SimpleDoubleProperty(0);
private DoubleProperty discount = new SimpleDoubleProperty(0);
private ReadOnlyDoubleWrapper subTotal = new ReadOnlyDoubleWrapper(0);
DUMMY_PurchaseOrderLine() {
subTotal.bind(quantity.multiply(unitPrice).subtract(discount));
}
IntegerProperty quantityProperty() { return quantity; }
IntegerProperty unitPriceProperty() { return unitPrice; }
IntegerProperty discountProperty() { return discount; }
ReadOnlyDoubleProperty subTotalProperty() { return subTotal.getReadOnlyProperty(); }
}
Note the naming conventions used. Using the correct naming convention is key.
I'm assuming here that the subtotal is just the calculated value for a single row (specifically by quantity * unitPrice - discount), not a total of values calculated across multiple rows (which would be quite a difficult problem to solve with a TableView).
Update based on question edit
I see from your update that you are using BigDecimal and JavaFX doesn't have a corresponding BigDecimalProperty, so either you will need to create one (not trivial if you want it to be fully featured) or use one of the existing property types.
Your alternate to using properties is to use the low level binding api to calculate subtotals, but I'd advise using properties if you can.
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.