Unable to insert values into tableview - JavaFx - tableview

I am new to JavaFx and I am trying to create a tableview and fxml is created using scene builder. If I run the program, the table is not getting the values. I found that this question is somehow matching with my requirement (javaFX 2.2 - Not able to populate table from Controller), but my code is matching with that too. But still I am not able to get the values in the table.
I have referenced the following video : http://www.youtube.com/watch?v=HiZ-glk9_LE
My code is as follows,
MainView.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class MainView extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
AnchorPane page = FXMLLoader.load(MainView.class.getResource("MainView.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Sample Window");
primaryStage.setResizable(false);
primaryStage.show();
} catch (Exception e) {
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="controller.MainViewController">
<children>
<SplitPane dividerPositions="0.535175879396985" focusTraversable="true" orientation="VERTICAL" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<TableView fx:id="tableID" prefHeight="210.0" prefWidth="598.0" tableMenuButtonVisible="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn minWidth="20.0" prefWidth="40.0" text="ID" fx:id="tID" />
<TableColumn prefWidth="100.0" text="Date" fx:id="tDate" />
<TableColumn prefWidth="200.0" text="Name" fx:id="tName" />
<TableColumn prefWidth="75.0" text="Price" fx:id="tPrice" />
</columns>
</TableView>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0" />
</items>
</SplitPane>
</children>
</AnchorPane>
MainViewController.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import model.Table;
/**
* FXML Controller class
*
*/
public class MainViewController implements Initializable {
/**
* Initializes the controller class.
*/
#FXML
TableView<Table> tableID;
#FXML
TableColumn<Table, Integer> tID;
#FXML
TableColumn<Table, String> tName;
#FXML
TableColumn<Table, String> tDate;
#FXML
TableColumn<Table, String> tPrice;
int iNumber = 1;
ObservableList<Table> data =
FXCollections.observableArrayList(
new Table(iNumber++, "Dinesh", "12/02/2013", "20"),
new Table(iNumber++, "Vignesh", "2/02/2013", "40"),
new Table(iNumber++, "Satheesh", "1/02/2013", "100"),
new Table(iNumber++, "Dinesh", "12/02/2013", "16"));
#Override
public void initialize(URL url, ResourceBundle rb) {
// System.out.println("called");
tID.setCellValueFactory(new PropertyValueFactory<Table, Integer>("rID"));
tName.setCellValueFactory(new PropertyValueFactory<Table, String>("rName"));
tDate.setCellValueFactory(new PropertyValueFactory<Table, String>("rDate"));
tPrice.setCellValueFactory(new PropertyValueFactory<Table, String>("rPrice"));
tableID.setItems(data);
}
}
Table.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Table {
SimpleIntegerProperty rID;
SimpleStringProperty rName;
SimpleStringProperty rDate;
SimpleStringProperty rPrice;
public Table(int rID, String rName, String rDate, String rPrice) {
this.rID = new SimpleIntegerProperty(rID);
this.rName = new SimpleStringProperty(rName);
this.rDate = new SimpleStringProperty(rDate);
this.rPrice = new SimpleStringProperty(rPrice);
System.out.println(rID);
System.out.println(rName);
System.out.println(rDate);
System.out.println(rPrice);
}
public Integer getrID() {
return rID.get();
}
public void setrID(Integer v) {
this.rID.set(v);
}
public String getrDate() {
return rDate.get();
}
public void setrDate(String d) {
this.rDate.set(d);
}
public String getrName() {
return rName.get();
}
public void setrName(String n) {
this.rDate.set(n);
}
public String getrPrice() {
return rPrice.get();
}
public void setrPrice(String p) {
this.rPrice.set(p);
}
}
Thanks in advance.

In a Table.java change all getters and setters names,
change getr* to getR*
change setr* to setR*

Thanks to #Uluk Biy. Whatever he mentioned, that needs to be changed and I found that I missed the <cellValueFactory> and <PropertyValueFactory> tags under the <TableColumn> tag for each columns in the FXML file which is as follows,
<TableColumn minWidth="20.0" prefWidth="40.0" text="ID" fx:id="tID" >
<cellValueFactory>
<PropertyValueFactory property="tID" />
</cellValueFactory>
</TableColumn>
Similar to this, all columns need to be updated like this.
After this change, the code is working fine. I am able to add the values into the row. :)

Related

How to show / hide / auto hide a node

I am doing a javafx project which if i click the button, the scene is showing, but if the scene is left open for few seconds, the scene will auto hide.
The actual scene is if i left it open, it will auto hide at the below of the main scene just like the button is pressed.
But i tried alot ways, the scene will either not hiding, or moving upward which if i click the button, the scene is at upward of the scene moving but not on the main scene.
If the scene is not on main scene, nothing will happen.But only if the scene is on main scene, the scene will auto hide and move downward just like when I click the button, the scene appear on the main scene from below and if i click close, the scene will go down and hide until i click again. when i click the button after a few inactive(like move the cursor), the scene will function as usual.
The code which i follow : Call another FXML within a stage
Testinggg.java
package testinggg;
import java.io.IOException;
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.InputEvent;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Testinggg extends Application {
private TestController controller;
#Override
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Test.fxml"));
Parent root = loader.load();
controller = loader.getController();
stage.setScene(new Scene(root));
stage.setFullScreen(true);
stage.show();
Duration duration = Duration.seconds(5);
PauseTransition transition = new PauseTransition(duration);
transition.setOnFinished(evt -> inactive());
stage.addEventFilter(InputEvent.ANY, evt -> transition.playFromStart());
transition.play();
}
private void inactive(){
//hide the status until status is open
}
public static void main(String[] args) {
launch(args);
}
}
TestController.java
package testinggg;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.TranslateTransition;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
public class TestController implements Initializable {
#FXML private VBox statusContainer;
private TranslateTransition showStatus;
private TranslateTransition hideStatus;
boolean showsStatus = false;
public void toggleStatus() {
if( showsStatus ) {
showStatus.stop();
hideStatus.play();
}
else {
hideStatus.stop();
showStatus.play();
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
showStatus = new TranslateTransition(Duration.millis(250), statusContainer);
showStatus.setByY(-1080.0);
showStatus.setOnFinished(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
showsStatus = true;
}
});
hideStatus = new TranslateTransition(Duration.millis(250), statusContainer);
hideStatus.setByY(1080.0);
hideStatus.setOnFinished(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
showsStatus = false;
}
});
}
}
for Test.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.web.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="1080.0" prefWidth="1920.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="testinggg.TestController">
<children>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" prefHeight="1080.0" prefWidth="1920.0" StackPane.alignment="TOP_LEFT">
<children>
<Button mnemonicParsing="false" onAction="#toggleStatus" prefHeight="1080.0" prefWidth="1920.0" text="Button" />
</children>
</AnchorPane>
<VBox fx:id="statusContainer" maxHeight="1080.0" prefHeight="1080.0" translateY="1080.0" StackPane.alignment="BOTTOM_LEFT">
<children>
<AnchorPane prefHeight="668.0" prefWidth="1266.0">
<VBox.margin>
<Insets bottom="50.0" left="50.0" right="50.0" top="50.0" />
</VBox.margin>
<children>
<ImageView fitHeight="540.0" fitWidth="1820.0" layoutY="43.0" pickOnBounds="true">
<image>
<Image url="#../Rainbow%20Poro.png" />
</image>
</ImageView>
<ImageView fitHeight="44.0" fitWidth="153.0" layoutX="857.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#../logo.png" />
</image>
</ImageView>
<ScrollPane layoutY="582.0" prefHeight="391.0" prefViewportHeight="208.0" prefViewportWidth="1266.0" prefWidth="1820.0">
<content>
<TextArea editable="false" layoutY="460.0" prefHeight="515.0" prefWidth="1804.0" text="Some paragraph here" />
</content>
</ScrollPane>
<Button layoutX="1775.0" mnemonicParsing="false" onAction="#toggleStatus" text="Close" />
</children>
</AnchorPane>
</children>
</VBox>
</children>
<stylesheets>
<URL value="#test1.css" />
</stylesheets>
</StackPane>
Here is an mcve version of the code you are following, to get you started :
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Test1 extends Application {
#Override
public void start(Stage primaryStage) {
try {
StackPane page = (StackPane) FXMLLoader.load(this.getClass().getResource("test1.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
test1.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>
<StackPane id="StackPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="300.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/10.0.1"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="Test1Controller">
<children>
<AnchorPane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: blue;">
<children>
<Button mnemonicParsing="false" onAction="#toggleStatus" text="Status" AnchorPane.leftAnchor="50.0" AnchorPane.topAnchor="100.0" />
</children>
</AnchorPane>
<VBox fx:id="statusContainer" maxHeight="100.0" prefHeight="100.0" style="-fx-background-color: yellow;" translateY="100.0" StackPane.alignment="BOTTOM_LEFT" />
</children>
</StackPane>
and its controller:
import javafx.animation.TranslateTransition;
import javafx.fxml.FXML;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
public class Test1Controller {
#FXML private VBox statusContainer;
private TranslateTransition showStatus;
private TranslateTransition hideStatus;
private boolean showsStatus = false;
#FXML void initialize() {
showStatus = new TranslateTransition(Duration.millis(250), statusContainer);
showStatus.setByY(-100.0);
showStatus.setOnFinished(event -> showsStatus = true);
hideStatus = new TranslateTransition(Duration.millis(250), statusContainer);
hideStatus.setByY(100.0);
hideStatus.setOnFinished(event -> showsStatus = false);
}
public void toggleStatus() {
if( showsStatus ) {
showStatus.stop();
hideStatus.play();
}
else {
hideStatus.stop();
showStatus.play();
}
}
}
Edit: you can add auto-hide of the sliding node to the controller:
public class Test1Controller {
#FXML private VBox statusContainer;
private TranslateTransition showStatus;
private TranslateTransition hideStatus;
private boolean showsStatus = false;
private static final int AUTO_HIDE_DEALY = 5;
#FXML void initialize() {
showStatus = new TranslateTransition(Duration.millis(250), statusContainer);
showStatus.setByY(-100.0);
showStatus.setOnFinished(event -> {
showsStatus = true;
autoHide();
});
hideStatus = new TranslateTransition(Duration.millis(250), statusContainer);
hideStatus.setByY(100.0);
hideStatus.setOnFinished(event -> showsStatus = false);
}
public void toggleStatus() {
if( showsStatus ) {
hide();
}
else {
show();
}
}
private void show(){
hideStatus.stop();
showStatus.play();
}
private void hide(){
showStatus.stop();
hideStatus.play();
}
private void autoHide() {
Duration duration = Duration.seconds(AUTO_HIDE_DEALY);
PauseTransition transition = new PauseTransition(duration);
transition.setOnFinished(evt ->{
if( showsStatus ) {
hide();
}
});
transition.play();
}
}

TableView not showing items [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.

javafx8 TableView Multiselection returns one of the selected items as null

TableView multi selection returns one of the selected objects as null. This doesn't happen every time but happens most of the times when i try to select two rows in the table.similar to the issue defined in this question
Best way of reproducing the issue is , try selecting two sequential rows .
FXML :
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ProgressBar?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Region?>
<?import javafx.scene.layout.StackPane?>
<AnchorPane xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.test.controller.TestController">
<children>
<TableView fx:id="personsTable" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="35.0">
<placeholder>
<Label text="" />
</placeholder>
<columns>
<TableColumn text="Name">
<cellValueFactory>
<PropertyValueFactory property="name" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Address">
<cellValueFactory>
<PropertyValueFactory property="address" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Course">
<cellValueFactory>
<PropertyValueFactory property="course" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Country">
<cellValueFactory>
<PropertyValueFactory property="country" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
</children>
</AnchorPane>
Controller :
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import com.test.model.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableView;
public class TestController implements Initializable {
#FXML
TableView<Person> personsTable = new TableView<Person>();
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
MenuItem combine = new MenuItem("Select");
combine.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
List<Person> selectedPersons = new ArrayList<Person>(
personsTable.getSelectionModel().getSelectedItems());
for (Person person : selectedPersons) {
System.out.println(" the object is " + person);
}
}
});
ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().add(combine);
personsTable.setContextMenu(contextMenu);
personsTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
personsTable.setItems(getPendingOrders());
}
public ObservableList<Person> getPendingOrders() {
ObservableList<Person> persons = FXCollections.observableArrayList();
for (int i = 0; i < 100; i++) {
Person person = new Person();
person.setName("Name" + i);
person.setAddress("Address" + i);
person.setCountry("Country" + i);
person.setCourse("Course" + i);
persons.add(person);
}
return persons;
}
}
Model :
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
private String name;
private String address;
private String country;
private String course;
}
1: add a default cell factory to your TableView
2: override either updateItem or updateIndex
hope it helpls

OSX EL CAPITAN ONLY - Popup appears offset when I move the ownerNode

THIS PROBLEM OCCURS ONLY ON OSX EL CAPITAN
There's a ListView, and when the user puts the mouse over a ListCell a popup with a picture related to the 'pointed' item should appear next to the cell.
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="36.0" prefWidth="572.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxswingapplication0.AddController">
<children>
<TextField fx:id="textField" onKeyReleased="#oneKeyReleasedTextField" prefHeight="27.0" prefWidth="499.0">
<HBox.margin>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
</HBox.margin>
</TextField>
<Button fx:id="myButton" mnemonicParsing="false" text="Button">
<HBox.margin>
<Insets bottom="5.0" right="5.0" top="5.0" />
</HBox.margin>
</Button>
</children>
</HBox>
Controller Class
package javafxswingapplication0;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Bounds;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.stage.Popup;
import javafx.util.Callback;
public class AddController implements Initializable {
#FXML
TextField textField;
#FXML
Button myButton;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
public void oneKeyReleasedTextField()
{
Popup resultsList = new Popup();
Bounds textFieldBounds = textField.localToScreen(textField.getBoundsInLocal());
ListView lsv = new ListView();
//add Data
ArrayList<String> sampleData = new ArrayList<String>(){{
add("Jamie");
add("Dyed");
add("Seth");
}};
ObservableList<String> sampleDataObservable = FXCollections.observableArrayList(sampleData);
lsv.setItems(sampleDataObservable);
//CellFactory
lsv.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> param) {
return new CustomCell();
}
});
//Style
lsv.setStyle("-fx-pref-width: " + textField.getWidth());
resultsList.getContent().add(lsv);
resultsList.show(textField, textFieldBounds.getMinX(), textFieldBounds.getMaxY());
}
}
class CustomCell extends ListCell<String>{
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item);
} else {
setText("");
}
ListCell<String> thisCell = this;
Popup image = new Popup();
setOnMouseEntered(new EventHandler(){
#Override
public void handle(Event event) {
image.getContent().add(new ImageView("http://theletter.co.uk/images/blog/2011/05/jamie-jones.jpg"));
Bounds thisCellBounds = thisCell.localToScreen(thisCell.getBoundsInLocal());
image.show(thisCell, thisCellBounds.getMaxX(), thisCellBounds.getMinY());
}
});
setOnMouseExited(new EventHandler(){
#Override
public void handle(Event event) {
image.hide();
}
});
}
}
It works fine if I don't move the window that contains the ListView.
On the contrary the Popup with the picture is displayed with an unexpected offset: the problem is that Cell's coordinates I get from "thisCell.localToScreen(thisCell.getBoundsInLocal())" aren't exact if I first moved the window.
What could the problem be?

updateItem's second param have never be false in javafx2

I use javafx2 control TableView to dispay records in the database(I have 20 records now).
And when display the record,I want to add button in each row.
so I search lots of article use google,and write some code below.
the key code is:
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
final Button button = new Button("modifty");
setGraphic(button);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
I debug this code,the param "empty" would never be "false",
so the button would never be display in the table view,
can anyone help me? thanks
below is the complete code(java and fxml):
java:
package com.turbooo.restaurant.interfaces.javafx;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import com.turbooo.restaurant.domain.Customer;
import com.turbooo.restaurant.domain.CustomerRepository;
import com.turbooo.restaurant.interfaces.facade.dto.CustomerDto;
import com.turbooo.restaurant.interfaces.facade.dto.assembler.CustomerDtoAssembler;
import com.turbooo.restaurant.util.ContextHolder;
import com.turbooo.restaurant.util.UTF8Control;
public class CustomerController implements Initializable {
#FXML
private TableView<CustomerDto> customerTableView;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
TableColumn<CustomerDto, Long> idCol = new TableColumn<CustomerDto, Long>("id");
idCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,Long>("id")
);
TableColumn<CustomerDto, String> nameCol = new TableColumn<CustomerDto, String>("name");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,String>("name")
);
TableColumn<CustomerDto, String> birthdayCol = new TableColumn<CustomerDto, String>("birthday");
birthdayCol.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<CustomerDto, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<CustomerDto, String> customer) {
if (customer.getValue() != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return new SimpleStringProperty(sdf.format(customer.getValue().getBirthday()));
} else {
return new SimpleStringProperty("");
}
}
});
TableColumn<CustomerDto, Long> actionCol = new TableColumn<CustomerDto, Long>("action");
actionCol.setCellFactory(
new Callback<TableColumn<CustomerDto,Long>, TableCell<CustomerDto,Long>>() {
#Override
public TableCell<CustomerDto, Long> call(TableColumn<CustomerDto, Long> arg0) {
final TableCell<CustomerDto, Long> cell = new TableCell<CustomerDto, Long>() {
#Override
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
final Button button = new Button("modifty");
setGraphic(button);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
};
return cell;
}
});
//TODO add button column
customerTableView.getColumns().addAll(idCol, nameCol, birthdayCol, actionCol);
loadData();
}
public void loadData() {
CustomerRepository cusRepo = (CustomerRepository)ContextHolder.getContext().getBean("customerRepository");
List<Customer> customers = cusRepo.findAll();
CustomerDtoAssembler customerDTOAssembler = new CustomerDtoAssembler();
List<CustomerDto> customerDtos = customerDTOAssembler.toDTOList(customers);
ObservableList<CustomerDto> data = FXCollections.observableArrayList(customerDtos);
customerTableView.setItems(data);
}
public void showNewDialog(ActionEvent event) {
ResourceBundle resourceBundle = ResourceBundle.getBundle(
"com/turbooo/restaurant/interfaces/javafx/customer_holder",
new UTF8Control());
Parent container = null;
try {
container = FXMLLoader.load(
getClass().getResource("customer_holder.fxml"),
resourceBundle);
} catch (IOException e) {
e.printStackTrace();
}
container.setUserData(this); //pass the controller, so can access LoadData function in other place later
Scene scene = new Scene(container, 400, 300);
Stage stage = new Stage();
stage.setScene(scene);
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
}
}
fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<BorderPane prefHeight="345.0" prefWidth="350.0" xmlns:fx="http://javafx.com/fxml" fx:controller="com.turbooo.restaurant.interfaces.javafx.CustomerController">
<center>
<TableView fx:id="customerTableView" prefHeight="200.0" prefWidth="200.0" />
</center>
<top>
<HBox alignment="CENTER_LEFT" prefHeight="42.0" prefWidth="350.0">
<children>
<Button text="new" onAction="#showNewDialog"/>
<Separator prefHeight="25.0" prefWidth="13.0" visible="false" />
<Button text="modify" />
<Separator prefHeight="25.0" prefWidth="15.0" visible="false" />
<Button text="delete" />
</children>
</HBox>
</top>
</BorderPane>
You haven't set a cellValueFactory for your action column, so it is always empty.
A simple way to do this is just to set the cell value to the id of the record.
actionCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,Long>("id")
);
Additionally, I created a simple example for creating a table with Add buttons in it, which you could reference if needed.

Resources