I am trying to make editable checkbox in a tableview, but it always display unchecked checkbox no matter the "selected" value in the object. Could someone hint me what is wrong in my code please? (it works for all others columns)
DataModel:
public class Kosmetyk
{
private final SimpleIntegerProperty lp;
private final SimpleStringProperty nazwa;
private final SimpleDoubleProperty cena;
private final SimpleStringProperty uwagi;
private final SimpleBooleanProperty czyZakupiono;
public Kosmetyk(Integer lp, String nazwa, Double cena, String uwagi, Boolean czyZakupiono)
{
super();
this.lp = new SimpleIntegerProperty(lp);
this.nazwa = new SimpleStringProperty(nazwa);
this.cena = new SimpleDoubleProperty(cena);
this.uwagi = new SimpleStringProperty(uwagi);
this.czyZakupiono = new SimpleBooleanProperty(czyZakupiono);
}
public Integer getLp()
{
return lp.get();
}
public String getNazwa()
{
return nazwa.get();
}
public Double getCena()
{
return cena.get();
}
public String getUwagi()
{
return uwagi.get();
}
public Boolean getCzyZakupiono()
{
return czyZakupiono.get();
}
public void setNazwa(String nazwa)
{
this.nazwa.set(nazwa);
}
public void setCena(Double cena)
{
this.cena.set(cena);
}
public void setUwagi(String uwagi)
{
this.uwagi.set(uwagi);
}
public void setCzyZakupiono(Boolean czyZakupiono)
{
this.czyZakupiono.set(czyZakupiono);
}
}
TableView controller:
public class SecondController implements Initializable
{
#FXML private TableView<Kosmetyk> tabela;
#FXML private TableColumn<Kosmetyk, Integer> lp;
#FXML private TableColumn<Kosmetyk, String> nazwa;
#FXML private TableColumn<Kosmetyk, Double> cena;
#FXML private TableColumn<Kosmetyk, String> uwagi;
#FXML private TableColumn<Kosmetyk, Boolean> czyZakupiono;// = new TableColumn<>("");
#FXML private Button buttonCancelMain;
#FXML private Button buttonAdd;
#FXML private Button buttonDelete;
String COMMA_DELIMITTER = ";";
String NEW_LINE_SEPARATOR = "\n";
String FILE_HEADER = "Lp.;Nazwa;Cena;Uwagi;Zakupiono";
private static ObservableList<Kosmetyk> ViewAble = FXCollections.observableArrayList();
public void Add(Kosmetyk kosmetyk)
{
ViewAble.add(kosmetyk);
}
#Override
public void initialize(URL location, ResourceBundle resources)
{
tabela.setEditable(true);
lp.setSortable(false);
lp.setCellValueFactory(column-> new ReadOnlyObjectWrapper<Integer>(tabela.getItems().indexOf(column.getValue()) + 1));
nazwa.setCellValueFactory(new PropertyValueFactory<Kosmetyk, String>("nazwa"));
cena.setCellValueFactory(new PropertyValueFactory<Kosmetyk, Double>("cena"));
uwagi.setCellValueFactory(new PropertyValueFactory<Kosmetyk, String>("uwagi"));
czyZakupiono.setCellValueFactory(new PropertyValueFactory<Kosmetyk, Boolean>("czyZakupiono"));
czyZakupiono.setCellFactory(CheckBoxTableCell.forTableColumn(czyZakupiono));
tabela.setItems(ViewAble);
//tabela.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
tabela.getSelectionModel().clearSelection();
nazwa.setCellFactory(TextFieldTableCell.<Kosmetyk>forTableColumn());
nazwa.setOnEditCommit
(
(CellEditEvent<Kosmetyk, String> t) ->
{
((Kosmetyk) t.getTableView().getItems().get(t.getTablePosition().getRow())).setNazwa(t.getNewValue());;
}
);
cena.setCellFactory(TextFieldTableCell.<Kosmetyk, Double>forTableColumn(new DoubleStringConverter()));
cena.setOnEditCommit
(
(CellEditEvent<Kosmetyk, Double> t) ->
{
((Kosmetyk) t.getTableView().getItems().get(t.getTablePosition().getRow())).setCena(t.getNewValue());;
}
);
uwagi.setCellFactory(TextFieldTableCell.<Kosmetyk>forTableColumn());
uwagi.setOnEditCommit
(
(CellEditEvent<Kosmetyk, String> t) ->
{
((Kosmetyk) t.getTableView().getItems().get(t.getTablePosition().getRow())).setUwagi(t.getNewValue());;
}
);
}
}
AddControler (used to get values and then add it to tableview):
public class AddController
{
#FXML private TextField txtNazwa;
#FXML private TextField txtCena;
#FXML private TextField txtUwagi;
#FXML private CheckBox cboxKupione;
#FXML private Button buttonCancelAdd;
#FXML private Button buttonAddWish;
SecondController SC = new SecondController();
public void AddWish()
{
if(txtNazwa.getText().length() > 0 && txtCena.getText().length() > 0 && txtUwagi.getText().length() > 0)
{
SC.Add(new Kosmetyk(0, txtNazwa.getText(), Double.valueOf(txtCena.getText()), txtUwagi.getText(), Boolean.valueOf(cboxKupione.isSelected())));
buttonAddWish.getScene().getWindow().hide();
}
}
}
Related
I'm new to android and this is the first time I'm using room in my application. Either insert operation is not performed or the database is not created or any other error.
I don't know what I'm doing wrong so I need your help.
This program is running but No result is displayed. Nothing is showing on the screen.
Here is my code-
please let me know what is wrong in this code and what I should do to correct it.
Car_details.java
#PrimaryKey
#NonNull
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("desc")
#Expose
private String desc;
#SerializedName("image")
#Expose
private String image;
CarDao.java-
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Car_Details car_details);
#Query("Select * from car_table")
LiveData<List<Car_Details>> selectAll();
CarListDatabase.java
private static CarListDatabase instance;
public abstract CarDao carDao();
public static synchronized CarListDatabase getInstance(Context context){
if(instance==null)
{
instance= Room.databaseBuilder(context.getApplicationContext(),
CarListDatabase.class,"Car_database").fallbackToDestructiveMigration()
.build();
}
return instance;
}
CarRepository.java
public void getCarList(){
CarlistInterface carlistInterface= retrofit.create(CarlistInterface.class);
Call<List<Car_Details>> carList= carlistInterface.carList();
carList.enqueue(new Callback<List<Car_Details>>() {
#Override
public void onResponse(Call<List<Car_Details>> call, final Response<List<Car_Details>> response) {
if(response.body() != null){
List<Car_Details> car_details = response.body();
for (int i = 0; i < car_details.size(); i++) {
String id=car_details.get(i).getId();
String names = car_details.get(i).getName();
String desc=car_details.get(i).getDesc();
String image= car_details.get(i).getImage();
Car_Details car = new Car_Details();
car .setId(id);
car .setName(names);
car .setDesc(desc);
car .setImage(image);
new InsertNoteAsyncTask(carDao).execute(car);
}
}
}
});
}
public LiveData<List<Car_Details>> getCarLists(){
return allCarList;
}
private static class InsertNoteAsyncTask extends AsyncTask<Car_Details,Void,Void> {
private CarDao carDao;
private InsertNoteAsyncTask(CarDao carDao){
this.carDao= carDao;
}
#Override
protected Void doInBackground(Car_Details... car_details) {
carDao.insert(car_details[0]);
return null;
}
CarViewModel.java
public CarViewModel(#NonNull Application application) {
super(application);
repository= new CarRepository(application);
carList= repository.getCarLists();
}
public LiveData<List<Car_Details>> getListLiveData() {
return carList;
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
repository = new CarRepository(this);
carViewModel = ViewModelProviders.of(this).get(CarViewModel.class);
recyclerView= findViewById(R.id.cars_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List = new ArrayList<>();
recyclerAdapter = new RecyclerAdapter(List);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter = new RecyclerAdapter(List);
recyclerView.setAdapter(recyclerAdapter);
carViewModel.getListLiveData().observe(this, new
Observer<java.util.List<Car_Details>>() {
#Override
public void onChanged(java.util.List<Car_Details> car_details) {
recyclerAdapter.setUserList(List);
}
});
repository.getCarList();
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter {
List<Car_Details> carList= new ArrayList<>();
public RecyclerAdapter(List<Car_Details> carList) {
this.carList = carList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater= LayoutInflater.from(parent.getContext());
View view= layoutInflater.inflate(R.layout.row_item,parent,false);
return new RecyclerAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.car_name.setText(carList.get(position).getName());
holder.car_desc.setText(carList.get(position).getDesc());
}
public void setUserList(List<Car_Details> userList) {
this.carList = userList;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return carList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView car_name,car_desc;
public ViewHolder(#NonNull View itemView) {
super(itemView);
car_name= itemView.findViewById(R.id.car_name);
car_desc= itemView.findViewById(R.id.car_desc);
}
}
}
#Override
public int getItemCount() {
return carList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView car_name,car_desc;
public ViewHolder(#NonNull View itemView) {
super(itemView);
car_name= itemView.findViewById(R.id.car_name);
car_desc= itemView.findViewById(R.id.car_desc);
}
}
}
There is nothing wrong with your insert operation with room.
The way you have used live date in your application seems wrong that's why your program is running but no result is coming.
You have to check the part where you are using live data.
Hope this help you out.
I have a javaFX 8 pane that contains a Piles TableView. When I select a Pile from the TableView, it queries a database and populates a second TableView with instances of LogExt. This second TableView includes a column of checkboxes mapped to the LogExt.selected boolean property.
When I run the application, I can't select any of the checkboxes.
LogExt:
public class LogExt {
private BooleanProperty selected = new SimpleBooleanProperty();
private Log log;
public LogExt(Log log) {
this.setSelected(false);
this.log = log;
}
public boolean isSelected() {
return selected.get();
}
public BooleanProperty selectedProperty() {
return selected;
}
public void setSelected(boolean selected) {
this.selected.set(selected);
}
public Log getLog() {
return log;
}
public void setLog(Log log) {
this.log = log;
}
}
The controller:
public class CustomOrderController {
#FXML
private RadioButton openRadio;
#FXML
private ToggleGroup stageGroup;
#FXML
private TableView<Pile> pileTableView;
#FXML
private TableColumn<Pile, String> pileNoCol;
#FXML
private TableColumn<Pile, String> speciesCol;
#FXML
private TableColumn<Pile, String> gradeCol;
#FXML
private TableColumn<Pile, String> logTypeCol;
#FXML
private TableColumn<Pile, String> pileStartCol;
#FXML
private TableView<LogExt> logTable;
#FXML
private TableColumn<LogExt, Boolean> selectedCol;
#FXML
private TableColumn<LogExt, String> logSpeciesCol;
#FXML
private TableColumn<LogExt, String> logGradeCol;
#FXML
private TableColumn<LogExt, String> lengthCol;
#FXML
private TableColumn<LogExt, String> diameterCol;
#FXML
private TableColumn<LogExt, String> footageCol;
#FXML
private TextField totalFootageField;
#FXML
private TextField selectedFootageField;
#FXML
private Button clearButton;
#FXML
private TextField reportNoField;
#FXML
private Button saveButton;
private ObservableList openPileList = null;
private ObservableList finishedPileList = null;
private final static Logger LOG = LoggerFactory.getLogger(CustomOrderController.class);
#FXML
protected void initialize() {
super.initialize();
// Set table columns to display proper values.
pileNoCol.setCellValueFactory(new PropertyValueFactory<>("pileNo"));
speciesCol.setCellValueFactory(param -> {
StringProperty stringProperty;
if (param.getValue().getSpecies() != null)
stringProperty = new SimpleStringProperty(param.getValue().getSpecies().getName());
else stringProperty = new SimpleStringProperty("All");
return stringProperty;
});
gradeCol.setCellValueFactory(param -> {
StringProperty grade;
if (param.getValue().getGrade() != null)
grade = new SimpleStringProperty(param.getValue().getGrade().getName());
else grade = new SimpleStringProperty("All");
return grade;
});
logTypeCol.setCellValueFactory(param -> {
StringProperty logType;
if (param.getValue().getLogType() != null)
logType = new SimpleStringProperty(param.getValue().getLogType().getName());
else logType = new SimpleStringProperty("All");
return logType;
});
pileStartCol.setCellValueFactory(param -> {
StringProperty startDate;
if (param.getValue().getPileStart() != null)
startDate = new SimpleStringProperty(
param.getValue().getPileStart().format(DATETIMEFORMATTER));
else startDate = null;
return startDate;
});
// Add listener to catch table selections.
pileTableView.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> selectPile());
// Add listener to catch radio button selections.
stageGroup.selectedToggleProperty().addListener((
observable, oldValue, newValue) -> changeList());
// Ensure values entered in the limit/warning fields are acceptable.
reportNoField.setTextFormatter(new TextFormatter<>(INTEGERSTRINGCONVERTER
, 0, POSINTEGERFILTER));
selectedCol.setCellValueFactory(new PropertyValueFactory<>("selected"));
selectedCol.setCellFactory(CheckBoxTableCell.forTableColumn(selectedCol));
logSpeciesCol.setCellValueFactory(param ->
new SimpleStringProperty(param.getValue().getLog().getSpecies().getName()));
logGradeCol.setCellValueFactory(param ->
new SimpleStringProperty(param.getValue().getLog().getLogGrade().getName()));
lengthCol.setCellValueFactory(param ->
new SimpleStringProperty(String.format("%d", param.getValue().getLog().getDeductionLength())));
diameterCol.setCellValueFactory(param ->
new SimpleStringProperty(String.format("%d", param.getValue().getLog().getDeductionDiameter())));
footageCol.setCellValueFactory(param ->
new SimpleStringProperty(String.format("%d", param.getValue().getLog().getNetFootage())));
}
protected void refreshPane() {
// Get the list of piles.
openPileList = FXCollections.observableList(HibernateUtil.getProgramsCommonDB().
query("from Pile where pileEnd = '" + NODATETIME.format(QUERYDATETIMEFORMATTER) + "'"));
finishedPileList = FXCollections.observableList(HibernateUtil.getProgramsCommonDB().
query("from Pile where pileEnd > '" + NODATETIME.format(QUERYDATETIMEFORMATTER) +
"' and consumeStart = '" + NODATETIME.format(QUERYDATETIMEFORMATTER) + "'"));
changeList();
// Set buttons and fields off to start.
clear();
}
private void changeList() {
clear();
if (openRadio.isSelected()) pileTableView.setItems(openPileList);
else pileTableView.setItems(finishedPileList);
}
private void enableWidgets(boolean yes) {
clearButton.setDisable(!yes);
logTable.setDisable(!yes);
reportNoField.setDisable(!yes);
LOG.info("OpenRadio: {}, enable: {}", openRadio.isSelected(), yes);
saveButton.setDisable(true);
}
private void clearWidgets() {
pileTableView.getSelectionModel().clearSelection();
logTable.getItems().clear();
totalFootageField.clear();
selectedFootageField.clear();
reportNoField.clear();
}
#FXML
private void clear() {
clearWidgets();
enableWidgets(false);
}
private void selectPile() {
Pile currentPile = pileTableView.getSelectionModel().getSelectedItem();
if (currentPile != null) {
// Fill the logs list with logs from this pile that have not been consumed.
List oList = HibernateUtil.getLogsDB().query("from Log where pileID = "
+ currentPile.getId()
+ " and (consumeTime is null or consumeTime = '"
+ NODATETIME.format(QUERYDATETIMEFORMATTER) + "')");
List<LogExt> logList = new ArrayList<>();
oList.forEach(o -> {
LogExt logExt = new LogExt((Log) o);
logList.add(logExt);
});
totalFootageField.setText(String.format("%d", logList.stream()
.mapToInt(value -> value.getLog().getNetFootage())
.sum()));
logTable.setItems(FXCollections.observableList(logList));
enableWidgets(true);
}
}
}
You need to enable editing on your table.
logTable.setEditable(true);
possibly on your column as well
selectedCol.setEditable(true);
I have these items:
#FXML
private Button bttnRemove;
#FXML
private TableView<EventsBean> eventsTable;
#FXML
private TableColumn<EventsBean, String> eventCol;
#FXML
private TableColumn<EventsBean, LocalDate> dateCol;
#FXML
private TableColumn<EventsBean, Boolean> doneCol;
#FXML
private TableColumn<EventsBean, String> observationCol;
#FXML
private TableColumn<EventsBean, Boolean> removeCol;
and in removeCol I create checkboxes:
ObservableList<EventsBean> dataList = FXCollections.observableArrayList();
#Override
public void initialize(URL location, ResourceBundle resources) {
removeCol.setCellFactory(CheckBoxTableCell.forTableColumn(removeCol));
removeCol.setCellValueFactory(new PropertyValueFactory<EventsBean, Boolean>("remove"));
eventsTable.setItems(dataList);
bttnAddEvent.setOnAction((ActionEvent e) -> {
text = eventsSelector.getValue().toString();
dataList.add(new EventsBean(text, isoDate, ""));
});
bttnRemove.setOnAction((ActionEvent e) -> {
//code here...
});
}
I want to use bttnRemove to delete a row that have checkbox checked from removeCol.
I find next solution that works very good:
public class EventsBean {
private SimpleStringProperty event;
private SimpleObjectProperty<LocalDate> date;
private SimpleStringProperty observation;
private SimpleBooleanProperty selected;
public EventsBean(String event, LocalDate date, String observation, boolean selected) {
this.event = new SimpleStringProperty(event);
this.date = new SimpleObjectProperty<LocalDate>(date);
this.observation = new SimpleStringProperty(observation);
this.selected = new SimpleBooleanProperty(selected);
}
// the other getters and setters
public boolean getSelected(){
return selectedProperty().get();
}
public SimpleBooleanProperty selectedProperty() {
return this.selected;
}
}
In my Controller class in initialize method:
removeCol.setCellValueFactory(cellData -> cellData.getValue().selectedProperty());
bttnRemove.setOnAction((ActionEvent e) -> {
ObservableList<EventsBean> dataListToRemove = FXCollections.observableArrayList();
for (EventsBean bean : dataList) {
if (bean.getSelected()) {
dataListToRemove.add(bean);
}
}
dataList.removeAll(dataListToRemove);
I would like to create a payroll program such that when the user tick a CheckBox in TableView, the name (String) will be carried on to the panel on the right and with TextFields to enter more info such as this:
I tried to follow the MVC hierarchy thus far as I code:
PayrollMainApp.java
public class PayrollMainApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Employee> selectEmployeeTable = FXCollections.observableArrayList();
public PayrollMainApp(){
selectEmployeeTable.add(new Employee(false,"Hans Muster"));
selectEmployeeTable.add(new Employee(true,"Ruth Mueller"));
selectEmployeeTable.add(new Employee(false,"Heinz Kurz"));
selectEmployeeTable.add(new Employee(false,"Cornelia Meier"));
selectEmployeeTable.add(new Employee(false,"Werner Meyer"));
selectEmployeeTable.add(new Employee(false,"Lydia Kunz"));
selectEmployeeTable.add(new Employee(false,"Anna Best"));
selectEmployeeTable.add(new Employee(false,"Stefan Meier"));
selectEmployeeTable.add(new Employee(false,"Martin Mueller"));
}
public ObservableList<Employee> getSelectEmployeeTable(){
return selectEmployeeTable;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("PayrollApp");
initRootLayout();
showEmployeeOverview();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(PayrollMainApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Shows the person overview inside the root layout.
*/
public void showEmployeeOverview() {
try {
// Load person overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(PayrollMainApp.class.getResource("view/EmployeeOverview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
// Set person overview into the center of root layout.
rootLayout.setCenter(personOverview);
// Give the controller access to the main app
EmployeeOverviewController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the main stage.
* #return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
Employee.java
public class Employee {
private BooleanProperty checkedBox = new SimpleBooleanProperty(false);
private StringProperty employeeName = new SimpleStringProperty();
public Employee(){
super();
}
public Employee(boolean checkedBox, String employeeName){
this.checkedBox = new SimpleBooleanProperty(false);
this.employeeName = new SimpleStringProperty(employeeName);
}
public BooleanProperty checkedBoxProperty(){
return this.checkedBox;
}
public StringProperty employeeNameProperty(){
return this.employeeName;
}
public java.lang.Boolean getSelectBox() {
return this.checkedBoxProperty().get();
}
public StringProperty getEmployeeName() {
return employeeName;
}
public void setSelectBox(final java.lang.Boolean checkedBox){
this.checkedBoxProperty().set(checkedBox);
}
public void setEmployeeName(StringProperty employeeName) {
this.employeeName = employeeName;
}
}
EmployeeOverviewController.java
public class EmployeeOverviewController {
#FXML
private TableView<Employee> selectEmployeeTable;
#FXML
private TableColumn<Employee, String> employeeNameColumn;
#FXML
private TableColumn<Employee, Boolean> checkBoxColumn;
private PayrollMainApp mainApp;
public EmployeeOverviewController() {
}
#FXML
public void initialize() {
checkBoxColumn.setCellValueFactory(cellData -> cellData.getValue().checkedBoxProperty());
checkBoxColumn.setCellFactory(param -> new CheckBoxTableCell<Employee, Boolean>());
employeeNameColumn.setCellValueFactory(cellData -> cellData.getValue().employeeNameProperty());
}
public void setMainApp(PayrollMainApp mainApp){
this.mainApp = mainApp;
//Add observable list data to the table
selectEmployeeTable.setItems(mainApp.getSelectEmployeeTable());
}
}
And a util class to make the checkBox visible in the table:
SelectBoxCellFactory.java
public class SelectBoxCellFactory implements Callback {
#Override
public TableCell call(Object param) {
CheckBoxTableCell<Employee,Boolean> checkBoxCell = new CheckBoxTableCell();
return checkBoxCell;
}
}
Here is my output thus far:
I know this has a table in it as compared to the previous output. Honestly I'm still indecisive as to use which, because I think using TextFields would make it look better. But all I hope for now is that this design is not impossible to code...
I really hope you can help me... Thank you for your help in advance.
It's probably easiest to use a TableView for the right panel. You can create a FilteredList from your original list:
FilteredList<Employee> selectedEmployees
= new FilteredList<>(selectEmployeeTable, Employee::getSelectBox);
and then use that for your second table.
If you prefer to use text fields (in what looks like a GridPane?) you can still use the filtered list above, but you will need to register a listener with it and update the layout "by hand" when items are added and removed.
I am building on Java FX application 3 weeks now and i have a problem i search things about that over the internet but i can't find the solution. I have to Populate Data on rows in a tableview i am getting data from database but i can't put it in the table i have this code that i use in order to take the data from Database.
public ObservableList<ObservableList> GetCustomerData(){
ObservableList<ObservableList> Data = FXCollections.observableArrayList();
try{
ConnectToDB();
DBStatement = DBConnection.createStatement();
DataRetrive = DBStatement.executeQuery("SELECT * FROM Customer");
while (DataRetrive.next()){
ObservableList<String> Row = FXCollections.observableArrayList();
Row.add(String.valueOf(DataRetrive.getInt(1)));
Row.add(DataRetrive.getString(2));
Row.add(DataRetrive.getString(3));
Row.add(DataRetrive.getString(4));
Row.add(DataRetrive.getString(5));
Row.add(DataRetrive.getString(6));
Row.add(DataRetrive.getString(7));
Row.add(DataRetrive.getString(8));
Row.add(DataRetrive.getString(9));
Data.add(Row);
}
CloseDB();
}catch(SQLException e){
e.printStackTrace();
}
return Data;
}
How can I add Data in table cells from this ObservableList?
It is good practice to have a separate class to CRUD operations:
public abstract class CustomerDML {
public static final String TABLE_NAME = "Customer";
QueryClass qc = new QueryClass();
public ObservableList<Map> getCustomerData() {
ObservableList<Map> productList = FXCollections.observableArrayList();
try {
qc.setPs(qc.getConn().prepareStatement("SELECT * FROM " + TABLE_NAME));
qc.setRs(qc.getPs().executeQuery());
while (qc.getRs().next()) {
Map<String, String> product = new HashMap<>();
product.put("cus_id", String.valueOf(qc.getRs().getInt("cus_id")));
product.put("name", qc.getRs().getString("name"));
product.put("age", String.valueOf(qc.getRs().getInt("age")));
product.put("telephone", qc.getRs().getString("telephone"));
productList.add(product);
}
return customerList;
} catch (SQLException ex) {
return null;
}
}
You can implement your QueryClass like below :
public class QueryClass {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
//private String query;
public QueryClass() {
conn = DBConnectionClass.myConnection();
}
//getters and setters
...
Lets assume the we have injected something like below to your controller from your fxml:
public class Customer_fxmlController extends CustomerDML implements Initializable {
#FXML
private TableView<Map> cusTable;
#FXML
private TableColumn idCol;
#FXML
private TableColumn nameCol;
#FXML
private TableColumn ageCol;
#FXML
private TableColumn telCol;
...
public void loadCustomers() {
idCol.setCellValueFactory(new MapValueFactory("cus_id"));
nameCol.setCellValueFactory(new MapValueFactory("name"));
ageCol.setCellValueFactory(new MapValueFactory("age"));
telCol.setCellValueFactory(new MapValueFactory("telephone"));
cusTable.setItems(getCustomerData());//Which returns a ObservableList<Map>
}