JavaFX tableview showing only last row of data repeatedly from MySQL database - mysql

I have a windows application where I want to populate my table of from MySQL database. I have written the code below to get data in table. I am able to get the database but while adding the rows in table it shows only last row (repeatedly as much the rows of in MySQL) from MySQL database.
public class ShowDatabase{
private static ObservableList<UserMaster> row;
private static ObservableList<String> col;
public static void buildData(TableView<UserMaster> tableview){
Connection c;
String SQL = "SELECT * from user_info";
UserMaster cm = new UserMaster();
try{
String colHeading[]={"Name","Course","e-mail","City"};
col = FXCollections.observableArrayList(colHeading);
row= FXCollections.observableArrayList();
c= DBConnection.connect();
ResultSet rs = c.createStatement().executeQuery(SQL);
TableColumn<UserMaster,String> colName = new TableColumn<UserMaster, String>(col.get(0));
colName.setMinWidth(200);
colName.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("name"));
TableColumn<UserMaster, String> colCourse = new TableColumn<UserMaster, String>(col.get(1));
colCourse.setMinWidth(200);
colCourse.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("course"));
TableColumn<UserMaster, String> colEmail = new TableColumn<UserMaster, String>(col.get(2));
colEmail.setMinWidth(200);
colEmail.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("email"));
TableColumn<UserMaster, String> colCity = new TableColumn<UserMaster, String>(col.get(3));
colCity.setMinWidth(200);
colCity.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("city"));
tableview.getColumns().addAll(colName,colCourse,colEmail,colCity);
//colMobile,colEmail,colDoj,colCity);
while(rs.next()){
ObservableList<UserMaster> data = FXCollections.observableArrayList();
cm.name.set(rs.getString("name"));
cm.course.set(rs.getString("course_name"));
cm.email.set(rs.getString("email"));
cm.city.set(rs.getString("city"));
row.add(cm);
System.out.println(row.get(0).getName());
}
tableview.setItems(row);
}catch(SQLException sqex){
sqex.printStackTrace();
System.out.println("Error on Building Data");
}
}
}
Code to build table (Application):
public class DisplayDatabase extends Application{
#Override
public void start(Stage stage) throws Exception {
stage.setFullScreen(false);
TableView tableview;
//TableView
tableview = new TableView();
DisplayDatabase.buildData(tableview);
//Adding GridPane
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(20,20,20,20));
gridPane.setHgap(5);
gridPane.setVgap(5);
//Main Scene
Scene scene = new Scene(tableview);
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
And the class to format Observable List:
public class UserMaster{
public SimpleStringProperty name = new SimpleStringProperty();
public SimpleStringProperty course = new SimpleStringProperty();
public SimpleIntegerProperty mobile = new SimpleIntegerProperty();
public SimpleStringProperty email = new SimpleStringProperty();
public ObjectProperty<Date> doj = new SimpleObjectProperty<Date>();
public SimpleStringProperty city = new SimpleStringProperty();
public String getName() {
return name.get();
}
public String getEmail() {
return email.get();
}
public String getCity() {
return city.get();
}
public String getCourse() {
return course.get();
}
}
Though I have 2 unique rows of data but it is showing only last row (same data) form database table repeatedly.
Here is the picture attachment for more clarity about problem.

Create new UserMaster on every iteration:
while(rs.next()){
UserMaster cm = new UserMaster();
cm.name.set(rs.getString("name"));
cm.course.set(rs.getString("course_name"));
cm.email.set(rs.getString("email"));
cm.city.set(rs.getString("city"));
row.add(cm);
}
tableview.setItems(row);

while(rs.next()){
cm.name.set(rs.getString("name"));
cm.course.set(rs.getString("course_name"));
cm.email.set(rs.getString("email"));
cm.city.set(rs.getString("city"));
row.add(new UserMaster(name,course,email,city));
}
tableview.setItems(row);
try this :)

Related

Adding new User to a table from MYSQL database using JavaFX is not working

I searched but couldn't find a solution because the examples on google search does not with my programming stil.
edit: I solved the problem in the addUser method.
The date format in MySQL is YYY-MM-DD. In my DatePicker it's DD.MM.YYY. How can get this fixed?
Do I have to change something in my database or in my java file?
package application;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
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.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
public class Main extends Application {
private BorderPane root;
private Scene scene;
private GridPane grid;
private Label lblFirstName;
private Label lblLastName;
private Label lblDOB;
private TextField txtFirstName;
private TextField txtLastName;
private DatePicker txtDOB;
private Button btnAdd;
private Button btnCancel;
private Button btnUpdate;
private HBox hbox;
private ButtonBar buttonBar;
private TableView<User> table;
final ObservableList<User> data = FXCollections.observableArrayList();
Connection conn;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/...";
String user = "root";
String password = "...";
#Override
public void start(Stage primaryStage) {
try {
CheckConnection();
root = new BorderPane();
grid = new GridPane();
// Create labels and textfields
lblFirstName = new Label("First Name");
lblFirstName.setFont(new Font("Times New Roman", 18));
lblFirstName.setPrefSize(100, 50);
lblLastName = new Label("Last Name");
lblLastName.setFont(new Font("Times New Roman", 18));
lblLastName.setPrefSize(100, 50);
lblDOB = new Label("DOB");
lblDOB.setFont(new Font("Times New Roman", 18));
lblDOB.setPrefSize(150, 50);
txtFirstName = new TextField();
txtLastName = new TextField();
txtDOB = new DatePicker();
// add to grid
grid.add(lblFirstName, 0, 0, 1, 1);
grid.add(txtFirstName, 1, 0, 1, 1);
grid.add(lblLastName, 0, 1, 1, 1);
grid.add(txtLastName, 1, 1, 1, 1);
grid.add(lblDOB, 0, 2, 1, 1);
grid.add(txtDOB, 1, 2, 1, 1);
grid.setHgap(10);
grid.setVgap(5);
grid.setPadding(new Insets(50, 10, 10, 30));
// Column constraints
ColumnConstraints column1 = new ColumnConstraints();
ColumnConstraints column2 = new ColumnConstraints();
grid.getColumnConstraints().add(column1);
grid.getColumnConstraints().add(column2);
column1.setPrefWidth(110);
column2.setPrefWidth(200);
// Buttons, Button Actions, ButtonBar
btnAdd = new Button("Add");
btnAdd.setPrefSize(40, 40);
btnAdd.setOnAction(e -> {
addUser();
});
btnCancel = new Button("Cancel");
btnCancel.setPrefSize(40, 40);
btnCancel.setOnAction(e -> {
clearFields();
});
btnUpdate = new Button("Update");
btnUpdate.setPrefSize(40, 40);
btnUpdate.setOnAction(e -> {
updateTable();
});
buttonBar = new ButtonBar();
buttonBar.getButtons().addAll(btnAdd, btnCancel, btnUpdate);
// add ButtonBar to HBox
hbox = new HBox();
hbox.getChildren().add(buttonBar);
hbox.setPadding(new Insets(10));
// create table
table = new TableView<>();
TableColumn<User, String> IDColumn = new TableColumn<User, String>("PersonID");
IDColumn.setPrefWidth(100);
IDColumn.setCellValueFactory(new PropertyValueFactory<>("personID"));
TableColumn<User, String> vornameColumn = new TableColumn<User, String>("First Name");
vornameColumn.setPrefWidth(100);
vornameColumn.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<User, String> nachnameColumn = new TableColumn<User, String>("Last Name");
nachnameColumn.setPrefWidth(100);
nachnameColumn.setCellValueFactory(new PropertyValueFactory<>("lastName"));
TableColumn<User, String> dobColumn = new TableColumn<User, String>("DOB");
dobColumn.setPrefWidth(100);
dobColumn.setCellValueFactory(new PropertyValueFactory<>("dob"));
table.getColumns().addAll(IDColumn, vornameColumn, nachnameColumn, dobColumn);
root.setCenter(table);
BorderPane.setMargin(table, new Insets(10, 10, 10, 10));
root.setLeft(grid);
root.setBottom(hbox);
scene = new Scene(root, 1000, 500);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void CheckConnection() {
conn = DBConnection.DbConnector();
if (conn == null) {
System.out.println("Connection Not Successful");
System.exit(1);
} else {
System.out.println("Connection Successful");
}
}
public void updateTable() {
data.clear();
try {
String query = "SELECT * FROM persons ";
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
while (rs.next()) {
data.add(new User(rs.getString("PersonID"), rs.getString("Firstname"), rs.getString("Lastname"),
rs.getString("DOB")
));
table.setItems(data);
}
pst.close();
rs.close();
} catch (Exception e1) {
System.err.println(e1);
}
}
public void addUser() {
try {
conn = DBConnection.DbConnector();
String query = "INSERT into persons (Firstname, Lastname, DOB) VALUES (?, ?, ?)";
pst = conn.prepareStatement(query);
pst.setString(1, txtFirstName.getText());
pst.setString(2, txtLastName.getText());
pst.setString(3, ((TextField)txtDOB.getEditor()).getText());
pst.executeUpdate();
pst.close();
} catch (Exception e2) {
System.err.println(e2);
}
}
public void clearFields() {
txtFirstName.clear();
txtLastName.clear();
txtDOB.setValue(null);
}
public static void main(String[] args) {
launch(args);
}
}
package application;
import javafx.beans.property.SimpleStringProperty;
public class User {
private SimpleStringProperty personID;
private SimpleStringProperty firstName;
private SimpleStringProperty lastName;
private SimpleStringProperty dob;
public User(String pID, String fName, String lName, String DOB) {
this.personID = new SimpleStringProperty(pID);
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.dob = new SimpleStringProperty(DOB);
}
// getter , setter
public String getPersonID() {
return personID.get();
}
public void setPersonenID(String pID) {
personID.set(pID);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lName) {
lastName.set(lName);
}
public String getDob() {
return dob.get();
}
public void setDob(String DOB) {
dob.set(DOB);
}
}
package application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
static String url ="jdbc:mysql://localhost:3306/...";
static String user ="root";
static String password="...";
public static Connection DbConnector(){
try{
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return null;
}
}
I understand from your comment that the data type of column DOB, in database table persons is DATE. Hence the format is irrelevant because even though the documentation for DATE type includes the following:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
I think this is misleading because according to the storage requirements documentation, a DATE value is stored in three bytes. So the format is only for human-readable display.
So since the format is irrelevant, your problem is basically how to get the DatePicker value and insert it into DOB column of persons database table.
Method getValue(), in class DatePicker, returns a LocalDate.
If you are using MySQL Connector, then according to the documentation, the DATE data type maps to java class java.sql.Date.
Therefore you need to convert java.time.LocalDate to java.sql.Date. You can do this by calling static method valueOf() in class java.sql.Date. Refer to this SO question.
Here is my rewritten version of your addUser() method. It uses try-with-resources.
public void addUser() {
String query = "INSERT into persons (Firstname, Lastname, DOB) VALUES (?, ?, ?)";
try (conn = DBConnection.DbConnector();
pst = conn.prepareStatement(query)) {
pst.setString(1, txtFirstName.getText());
pst.setString(2, txtLastName.getText());
pst.setDate(3, java.sql.Date.valueOf(txtDOB.getValue()));
pst.executeUpdate();
}
catch (SQLException xSql) {
xSql.printStackTrace();
}
}
If you still also want to change the format of the date displayed by DatePicker, you can set its converter property. The below code demonstrates how to do this using an anonymous class.
DatePicker txtDOB = new DatePicker();
txtDOB.setConverter(new StringConverter<LocalDate>() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.ENGLISH);
#Override
public String toString(LocalDate object) {
if (object != null) {
return object.format(formatter);
}
return null;
}
#Override
public LocalDate fromString(String string) {
if (string != null) {
return LocalDate.parse(string, formatter);
}
return null;
}
});

Display Json data in unity

I want to create scoreboard with Firebase in Unity.
I know how to access data but I have problem with displaying these on screen.
I tried to add user data to list but I'm not sure if this is a good idea or if this will actually work
Here is my code:
public class Scoresmulti : MonoBehaviour
{
//Zliczanie punktów i wyświetlanie wyniku
public static int pointssum = 0;
public Text points;
private string user;
public String scoresboard;
public Array Scores;
public List<USers> scores = new List<USers>();
USers users = new USers();
public static fsSerializer serializer = new fsSerializer();
void Start()
{
//Posttodb();
Debug.Log("wykonano");
Getdata();
}
private void getscore()
{
//display text
}
void Update()
{
points.text = "Poprawne odpowiedzi: " + pointssum;
}
private void Posttodb()
{ user = nazwagracza.Playernick;
if (user != null)
{
USers users = new USers();
RestClient.Put("https://quizgame-inz.firebaseio.com/names/" + user + ".json", users);
}
}
private void Getdata()
{
StringBuilder builder = new StringBuilder();
RestClient.Get("https://quizgame-inz.firebaseio.com/.json").Then(response =>
{
fsData userdata = fsJsonParser.Parse(response.Text);
USers[] users = null;
serializer.TryDeserialize(userdata, ref users);
foreach (var user in users)
{
scores.Add(user);
}
});
}
}

Junit Mockito for global java.util.Map

I am trying to Test a method but it has a global variable which is null, Please guide me so I can assign value to global variable i.e. a Map
My Junit:
public class ErrorTest {
#Mock
private DataSource db;
#Mock
private JdbcTemplate jdbcTemplate;
#InjectMocks
private RateServiceImpl rateService = new RateServiceImpl();
#Mock
private RaterDao raterDao;
#Resource
private MessageSource msg ;
#Mock
Map<String, StringAttribute> errorMap = new HashMap<String, StringAttribute>();
#Before
public void setup() throws IOException, InterruptedException {
MockitoAnnotations.initMocks(this);
MockMvcBuilders.standaloneSetup(rateService).build();
}
#Test
public void findAllErrors() throws Exception {
String error;
List<Error> erList = new ArrayList<>();
Error er27 = new ErrorImpl("27",
"No detail found",
"Please enter detail.");
erList.add(er27);
Error er22 = new ErrorImpl("1",
"Maximum number exceeded",
"Please contact Technical Support.");
erList.add(er22);
for (int index = 0; index < erList.size(); index++) {
StringAttribute st = new StringAttributeImpl();
st.setName(erList.get(index).getDescription());
st.setValue(erList.get(index).getResolution());
errorMap.put(erList.get(index).getCode(), st);
}
List<Error> errorList = raterDao.findAllErrors();
assertThat(errorList, is(notNullValue()));
StringAttribute map27 = errorMap.get("27");
Mockito.when(rateService.findRwxlClientError("27")).thenReturn(map27);
StringAttribute map22 = errorMap.get("22");
Mockito.when(rateService.findRwxlClientError("22")).thenReturn(map22);
assertTrue("ParseShipment failed", map27.getName().equals("No detail found"));
assertTrue("ParseShipment failed", map22.getName().equals("Please contact Technical Support."));
}
}
My Main Class:
#Service
public class RateServiceImpl implements RateService {
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private RaterDao raterDao;
private Map<String, StringAttribute> errorMap = new HashMap<String, StringAttribute>();
#Resource
private MessageSource msg;
#PostConstruct
public void init() throws Exception {
**errorMap** = findAllClientErrors();
}
public Map<String, StringAttribute> findAllClientErrors() throws Exception {
List<Error> errorList = raterDao.findAllClientErrors();
for (int index = 0; index < errorList.size(); index++) {
StringAttribute st = new StringAttributeImpl();
st.setName(errorList.get(index).getDescription());
st.setValue(errorList.get(index).getResolution());
errorMap.put(errorList.get(index).getCode(), st);
}
return errorMap;
}
#Override
public StringAttribute findClientError(String code) throws Exception {
StringAttribute error = new StringAttributeImpl();
if (code.equals(Constants.ERROR_CODE_SETTING_UNAVAILABLE)) {
error.setName(msg.getMessage("SETTING.MESSAGE.ERROR", null,null));
error.setValue(msg.getMessage("SETTING.MESSAGE.RESOLUTION", null,null));
return error;
}
StringAttribute map = errorMap.get(code);
if (map == null || map.getName().isEmpty()) {
error.setName(msg.getMessage("DEFAULT.MESSAGE", new Object[] { code }, null));
error.setValue("");
} else {
error.setName(errorMap.get(code).getName());
error.setValue(errorMap.get(code).getValue());
}
return error;
}
}
I tried multiple solution but doesn't work, some time map becomes empty or null.
Any solution works which pass my test case.
I want to test findClientError(String code) and the issue is with errorMap
So, you can use ReflectionUtils.setField method. I made a small example, it is not exactly like your code, but overall you will get the idea.
So here's my class under test. Doing almost exactly like your example. I have hello method just to test and check if it is working or not.
class RateService {
private static Map<String, Object> errorMap = new HashMap<>();
#PostConstruct
public void init () {
this.errorMap = findAllErrors();
}
private Map<String, Object> findAllErrors() {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("a", new Object());
errorMap.put("b", new Object());
errorMap.put("c", new Object());
return errorMap;
}
// a method for demo purposes
public String hello() {
if (errorMap.size() > 0) {
return String.join(",", errorMap.keySet());
} else {
return "Empty";
}
}
}
Here's my test class. The third argument of the setField method is the object that is going to be set in that field. So, you can create a mock, or real object there. I assigned a real object with dummy values. Then tested against that.
class MainTest {
private RateService rateService;
#BeforeEach
void setUp() {
this.rateService = new RateService();
}
private Map<String, Object> exampleErrorObjects() {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("x", new Object());
errorMap.put("y", new Object());
errorMap.put("z", new Object());
return errorMap;
}
#Test
void testHello() {
// given:
ReflectionTestUtils.setField(RateService.class, "errorMap", exampleErrorObjects());
// when:
final String result = this.rateService.hello();
// then:
assertEquals("x,y,z", result);
}
}
I am setting the static field in a test method because you may want your class to be in different states (based on the errorMap field) in each test.

Playframework 2.5 [Java]: I can't insert one column data to my database

I'm using MySQL with Play, when I use Ebean to save data, all the data seems to be there except one column.
The following is my account entity:
#Entity
public class Account extends Model {
public static final int SUPER_ADMIN_COMPANY = -1;
#Id
#Column(length=16)
public String id;
#Constraints.MinLength(5)
#Constraints.MaxLength(100)
//#Constraints.Required
#Column(nullable=false, length=100,unique=true)
public String username;
/**password is not required if type is not 0*/
#JsonIgnore
//#Column(nullable=false)
public String password;
public String nicname;
public String mobile;
public String email;
#ManyToOne
public Company company;
#Index
#JsonIgnore
#Column(nullable=false)
public Date createTime;
#Column(nullable=false)
public Integer roleType; // 0 = super admin, 1 = admin, 2 = user
#Column(nullable=false)
public Boolean isEnabled = true;
public static Find<String, Account> finder =
new Find<String, Account>(){};
public static final int E_SUPERADMIN = 0;
public static final int E_ADMIN = 1;
public static final int E_USER = 2;
}
Also, this is my read method:
public Result create() {
Form<Account> form = formFactory.form(Account.class);
try {
String userId = session("userId");
Account adminAccount = Account.finder.byId(userId);
if (adminAccount == null) {
throw new CodeException(ErrDefinition.E_ACCOUNT_INCORRECT_PARAM);
}
if (adminAccount.roleType != 0 && adminAccount.roleType !=1) {
throw new CodeException(ErrDefinition.E_ACCOUNT_UNAUTHENTICATED);
}
//TODO
/*
if (!Authority.hasAccessRight(authority.accessRight, Authority.E_AUTHORITY_MENU)) {
throw new CodeException(ErrDefinition.E_ACCOUNT_UNAUTHENTICATED);
}
*/
if (form.hasErrors()) {
throw new CodeException(ErrDefinition.E_ACCOUNT_INCORRECT_PARAM);
}
Account newAccount = form.bindFromRequest().get();
if (Account.finder.where().eq("username", newAccount.username).findRowCount() != 0) {
throw new CodeException(ErrDefinition.E_ACCOUNT_ALREADY_EXIST);
}
if (newAccount.password == null || newAccount.password.isEmpty()) {
throw new CodeException(ErrDefinition.E_ACCOUNT_NO_PASSWORD);
}
if (newAccount.password != null && !newAccount.password.isEmpty()) {
newAccount.password = CodeGenerator.generateMD5(newAccount.password);
}
newAccount.id = CodeGenerator.generateShortUUId();
newAccount.createTime = new Date();
// if (newAccount.roleType < 0 || newAccount.roleType > 2) {
// throw new CodeException(ErrDefinition.E_ACCOUNT_INCORRECT_PARAM);
// }
if (adminAccount.roleType == 0) {
if (newAccount.roleType == 1) {
newAccount.roleType = 1;
}
else{
newAccount.roleType = 2;
}
}
else{
newAccount.roleType = 2;
}
newAccount.isEnabled = true;
Ebean.save(newAccount);
return success("id", newAccount.id);
}
catch (CodeException ce) {
Logger.error(ce.getMessage());
return failure(ce.getCode());
}
catch (Throwable e) {
e.printStackTrace();
Logger.error(e.getMessage());
return failure(ErrDefinition.E_ACCOUNT_CREATE_FAILED);
}
}
The following is my MySql data:
enter image description here
I use postman to test the read interface,and also input company_id data,but it was not successgful. How could I resolve this?
edit
#ManyToOne
#JoinColumn(name = "company_id", referencedColumnName = "company_id")
private Company company;
so adding the "referencedColumnName" to refer to the column in the company table conclusively solved this issue for me (tested) (you should also have the #OneToMany annotation as described below).
old answer:
I think you need to use a join column for the ManyToOne relationship,
#ManyToOne
#JoinColumn(name = "company_id")
public Company company;
edit:
You probably also need something like this in your Company class (could you post your existing code for it?):
#OneToMany(mappedBy = "company")
private List<Accounts> accounts = new Arraylist<>();

only one Column was populated in my Tableview

i'm populating my tableview from mysql database but only the column ID is the only one that's populated.
my main:
public void populate() throws Exception{
ObservableList<userdata1> data = FXCollections.observableArrayList();
tableView();
try{
String query = "select * from members";
ps = new Connect().connectDatabase1();
rs = ps.executeQuery(query);
while(rs.next()){
data.add(new userdata1(rs.getInt(1),rs.getString(2),rs.getInt(3)));
tblView.setItems(data);
}
}catch(Exception e){
System.out.print("asdqweasd");
}
}
public void tableView()throws Exception{
tblView.getItems().clear();
tblView.getColumns().clear();
rs = ps.executeQuery("SELECT * FROM members");
ObservableList<userdata1> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ID");
column1.setMinWidth(85);
column1.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("ID"));
TableColumn column2 = new TableColumn("Name");
column2.setMinWidth(565);
column2.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("comp_name"));
TableColumn column3 = new TableColumn("STATUS");
column3.setMinWidth(123);
column3.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("mem_status"));
tblView.getColumns().addAll(column1,column2,column3);
}
my userdata1:
public class userdata1 {
public SimpleIntegerProperty ID;
public SimpleStringProperty comp_name;
public SimpleIntegerProperty mem_status;
public userdata1(Integer id, String comp_name, Integer mem_status){
this.ID = new SimpleIntegerProperty(id);
this.comp_name = new SimpleStringProperty(comp_name);
this.mem_status = new SimpleIntegerProperty(mem_status);
}
public Integer getID() {
return ID.get();
}
public String getcomp_name(){
return comp_name.get();
}
public Integer getmem_status() {
return mem_status.get();
}
public void setID(Integer id) {
this.ID.set(id);
}
public void setcomp_name(String comp_name ) {
this.comp_name.set(comp_name);
}
public void setmem_status(Integer mem_status) {
this.mem_status.set(mem_status);
}
}
the data mem_status and comp_name is not populating their respective columns
As UserData1 already contains Properties, you can set the according Property to the cellValueFactory:
public class UserData1 {
private StringProperty comp_name;
//additional fields, getters and setters
public StringProperty comp_nameProperty() {
return comp_name;
}
}
setCellValueFactory(cellData -> cellData.getValue().comp_nameProperty());
If you want to stick to the PropertyValueFactory you have to access the fields according to the CamelCase convention:
column2.setCellValueFactory(new PropertyValueFactory<>("comp_name"));
public class UserData1 {
//...
public String getComp_name(){
return comp_name.get();
}
}