my code is working to 90% I think.
The Output is right, but not all columns are shown in the tableview.
I don't know where the problem is.
The fx:id is right, the code too, I believe.
Here's a picture of the openend program. I will give you also my output an my controller an table-code. The launching code isn't important.
Picture:
http://www.directupload.net/file/d/3791/aitj4rff_png.htm
Output:
*** Loaded Oracle-Driver ***
*** Connected with Database ***
Film: Hugo Gesehen: JA
Film: FAST and FURIOS 6 Gesehen: JA
Film: Emil Gesehen: NEIN
Film: DAS_BOOT Gesehen: JA
*** Database data saved to Observable List named 'data'
*** Table Items setted ***
table_controller:
package controller;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import oracle.jdbc.*;
import model.filmtable_data;
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;
#SuppressWarnings("unused")
public class table_controller implements Initializable {
private ObservableList<filmtable_data> filmData = FXCollections.observableArrayList();
#FXML
private TableView<filmtable_data> FilmTable;
#FXML
private TableColumn<filmtable_data, String> Filmtitel_Col;
#FXML
private TableColumn<filmtable_data, Integer> ID_Col;
#FXML
private TableColumn<filmtable_data, String> Gesehen_Col;
#Override
public void initialize(URL location, ResourceBundle resources) {
// Observable List
ID_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, Integer>("rID"));
Filmtitel_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, String>("rFilmtitel"));
Gesehen_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, String>("rGesehen"));
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("*** Loaded Oracle-Driver ***");
} catch (ClassNotFoundException e1) {
System.out.println("Driver-Loading failed.");
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:lukas/1234#10.140.79.39:1521:OTTO");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("SELECT FILMTITEL, GESEHEN FROM LUKA1");
String filmtitel = "empty";
String gesehen = "empty";
int zaehler = 1;
System.out.println("*** Connected with Database ***");
while (resultset.next()) {
filmtitel = resultset.getString("FILMTITEL");
gesehen = resultset.getString("GESEHEN");
System.out.println("Film: " + filmtitel + "\t\t\tGesehen: " + gesehen);
filmtable_data entry = new filmtable_data(zaehler, filmtitel, gesehen);
filmData.add(entry);
zaehler++;
}
System.out.println("*** Database data saved to Observable List named 'data'");
FilmTable.setItems(filmData);
System.out.println("*** Table Items setted ***");
statement.close();
} catch (SQLException e) {
System.out.println("Login fehlgeschlagen.");
e.printStackTrace();
}
}
}
filmtable_data:
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class filmtable_data {
private final SimpleIntegerProperty rID;
private final SimpleStringProperty rFilmtitel;
private final SimpleStringProperty rGesehen;
public filmtable_data (Integer sID, String sFilmtitel, String sGesehen) {
this.rID = new SimpleIntegerProperty(sID);
this.rFilmtitel = new SimpleStringProperty(sFilmtitel);
this.rGesehen = new SimpleStringProperty(sGesehen);
}
public Integer getRID() {
return rID.get();
}
public void setRID(int set) {
rID.set(set);
}
public String getRFilmtitel() {
return rFilmtitel.get();
}
public void setRFilmtitel(String set) {
rFilmtitel.set(set);
}
public String setRGesehen() {
return rGesehen.get();
}
public void setRGesehen(String set) {
rGesehen.set(set);
}
}
the fx-file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="366.0" prefWidth="268.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.table_controller">
<children>
<TableView fx:id="FilmTable" prefHeight="366.0" prefWidth="425.0">
<columns>
<TableColumn fx:id="ID_Col" minWidth="-Infinity" prefWidth="43.0" text="ID" />
<TableColumn fx:id="Filmtitel_Col" prefWidth="137.0" text="Filmtitel" />
<TableColumn fx:id="Gesehen_Col" prefWidth="137.0" text="Gesehen" />
</columns>
</TableView>
</children>
</AnchorPane>
You have a typo in your POJO class, and there is not getter:
This is wrong:
public String setRGesehen() {
return rGesehen.get();
}
It should be:
public String getRGesehen() {
return rGesehen.get();
}
Notice you should add also the property methods, like:
public StringProperty rGesehenProperty() {
return rGesehen;
}
Even with the wrong getter, as the PropertyValueFactory looks first for the property, it would have worked.
Related
I have a list application what is uses RecyclerView.
Each line has got a button, a checkbox and 2 textview.
All object is defined the RecyclerView clas, but I would like to check the checkbox status in the Main class and evaluate the status and remove the item from the list and from the SharedPreferences where the checkbox is checked
Main class is here:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
}
#Override
public void onItemClick(View view, int position) {
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
At now the item is removed when the whole line is touched. I would like to exchange to if only the Checkbox is "true".
At now the remove method is in the public void onItemClick(View view, int position) function.
I would like to put the content of the OnItemClick method to "if" part of CheckBox status.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
holder.myTextView.setText(meta_data);
holder.subtext.setText(meta_subdata +" "+ meta_subdata2);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = holder.myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView myTextView, subtext;
public Button add;
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done = itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
if(adapter.done.isChecked())should work I think, but I got null opbject reference exception.
Maybe the problem is that the checkbox is in the RecyclerView layout and not in Main class layout, but I am not sure.
Is it possible to handle the Checkbox methods from other class, and if yes, then where should I improve the code?
So ... I just started using databases and my brother recommended me to use H2 with EclipseLink to start. Did a quick Google search and found a Tutuorial:
https://www.javatips.net/blog/eclipselink-jpa-with-h2-database
https://www.javatips.net/blog/java-persistence-jpa-2-0-tutorial-with-eclipselink
If I code it like it is described in the Tutorial i get no error when i run it, but i check the database my Table is still empty. I searched for like a week now but i dont find an answer.
My Code:
Class Student
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENT")
public class Student implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "STUDENTID")
private long studentId;
#Column(name = "STUDENTNAME")
private String studentName;
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public long getStudentId() {
return studentId;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentName() {
return studentName;
}
}
JPAExample
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
public class JPAExample {
private EntityManager entityManager = EntityManagerUtil.getEntityManager();
public static void main(String[] args) {
JPAExample example = new JPAExample();
System.out.println("After Sucessfully insertion ");
Student student1 = example.saveStudent("Sumith");
Student student2 = example.saveStudent("Anoop");
example.listStudent();
System.out.println("After Sucessfully modification ");
example.updateStudent(student1.getStudentId(), "Sumith Honai");
example.updateStudent(student2.getStudentId(), "Anoop Pavanai");
example.listStudent();
System.out.println("After Sucessfully deletion ");
example.deleteStudent(student2.getStudentId());
example.listStudent();
}
public Student saveStudent(String studentName) {
Student student = new Student();
try {
entityManager.getTransaction().begin();
student.setStudentName(studentName);
student = entityManager.merge(student);
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
return student;
}
public void listStudent() {
try {
entityManager.getTransaction().begin();
#SuppressWarnings("unchecked")
List<Student> Students = entityManager.createQuery("from Student").getResultList();
for (Iterator<Student> iterator = Students.iterator(); iterator.hasNext();) {
Student student = (Student) iterator.next();
System.out.println(student.getStudentName());
}
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
public void updateStudent(Long studentId, String studentName) {
try {
entityManager.getTransaction().begin();
Student student = (Student) entityManager.find(Student.class, studentId);
student.setStudentName(studentName);
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
public void deleteStudent(Long studentId) {
try {
entityManager.getTransaction().begin();
Student student = (Student) entityManager.find(Student.class, studentId);
entityManager.remove(student);
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
}
EntityManagerUtil
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerUtil {
private static final EntityManagerFactory entityManagerFactory;
static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("test");
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManager getEntityManager() {
return entityManagerFactory.createEntityManager();
}
}
Persistence.xml
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<class>Student</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
When i run the JPAExample i get this output:
My Output
But the expected Output should look like this:
Expected Output
And if i look into the H2 Database nothing has changed:
H2 Database Interface (German Language)
Hope someone can help me or can link me a usefull/better JPA Tutorial :)
You are catching exceptions but not acknowledging or logging them - you should make sure you at least log it.
In this case, your listStudent method is getting an exception on
entityManager.createQuery("from Student").getResultList()
as this is an invalid JPQL query. You should be using something like:
entityManager.createQuery("select s from Student s").getResultList()
I am new to stackoverflow and to Java. I am trying to fetch the data from the database then display it in a JSF page.
For the table I have a model : BusesInfo.java that contains getters and setters for the attributes of the table.
then I also have BusesDao that fetches the data from DB and stores it in an array list. BusesInfoBean that links these data to the JSF page. The connection to the database is success. the JSF page contains a table that calls BusesInfobean.busesInfo in the columns i call BusesInfo.attribute
Please I need your help! Below you can find sample codes:
package beans;
import daos.BusesDao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import models.BusesInfo;
#ViewScoped
public class BusesInfoBean implements Serializable {
private final BusesDao busesDao = new BusesDao();
private ArrayList<BusesInfo> busesInfo;
public BusesInfoBean(){}
#PostConstruct
public void init(){
try {
busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(ManageEventsBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<BusesInfo> getBusesInfo() {
return busesInfo;
}
public void setBusesInfo(ArrayList<BusesInfo> busesInfo) {
this.busesInfo = busesInfo;
}
}
BusesDao.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import models.BusesInfo;
import java.util.logging.Logger;
import java.util.logging.Level;
public class BusesDao extends ConnectionDao {
public ArrayList<BusesInfo> buildBusesInfo() throws Exception {
ArrayList<BusesInfo> list = new ArrayList<>();
Connection conn = getConnection();
try {
String sql = "SELECT * FROM BUSES_INFO";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(populateBusesInfo(rs));
}
rs.close();
ps.close();
return list;
} catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
private BusesInfo populateBusesInfo(ResultSet rs) throws SQLException {
BusesInfo busesInfo = new BusesInfo();
busesInfo.setBusID(rs.getInt("BUS_ID"));
busesInfo.setDriverID(rs.getInt("DRIVER_ID"));
busesInfo.setDepartureTime(rs.getString("DEPARTURE_TIME"));
busesInfo.setArrivalTime(rs.getString("ARRIVAL_TIME"));
busesInfo.setRouteEn(rs.getString("ROUTE_EN"));
busesInfo.setRouteAr(rs.getString("ROUTE_AR"));
busesInfo.setLicensePlate(rs.getString("LICENSE_PLATE"));
busesInfo.setCapacity(rs.getInt("CAPACITY"));
return busesInfo;
}
public static void main(String [] args){
try {
BusesDao busesDao = new BusesDao();
ArrayList<BusesInfo> busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(EventsDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
the model class BusesInfo only contains getters and setters:
public class BusesInfo implements Serializable {
private int busID;
private int driverID;
private String departureTime;
private String arrivalTime;
private String routeEn;
private String routeAr;
private String licensePlate;
private int capacity;
public BusesInfo(){}
/**
*
* #param busID
* #param driverID
* #param departureTime
* #param arrivalTime
* #param routeEn
* #param routeAr
* #param licensePlate
* #param capacity
*/
public BusesInfo(int busID, int driverID, String departureTime, String arrivalTime, String routeEn, String routeAr, String licensePlate, int capacity) {
this.busID = busID;
this.driverID = driverID;
this.departureTime = departureTime;
this.arrivalTime = arrivalTime;
this.routeEn = routeEn;
this.routeAr = routeAr;
this.licensePlate = licensePlate;
this.capacity = capacity;
}
public int getBusID() {
return busID;
}
public void setBusID(int busID) {
this.busID = busID;
}
public int getDriverID() {
return driverID;
}
public void setDriverID(int driverID) {
this.driverID = driverID;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getRouteEn() {
return routeEn;
}
public void setRouteEn(String routeEn) {
this.routeEn = routeEn;
}
public String getRouteAr() {
return routeAr;
}
public void setRouteAr(String routeAr) {
this.routeAr = routeAr;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
JSF page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>#{msgs.buses}</title>
</h:head>
<h:body>
<div>
<ui:decorate template="/app_templates/app_template.xhtml">
<h:form id="bus_info_form">
<p:dataTable
id="bus_info_tbl"
value = "#{busesInfoBean.busesInfo}"
class = "dataTable"
var="event"
rows="2"
dir="#{langBean.dir}"
emptyMessage="#{msgs.no_buses}"
paginator="true"
paginatorPosition="top"
paginatorTemplate="#{langBean.isEnglish? '{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}' : '{RowsPerPageDropdown} {LastPageLink} {NextPageLink} {PageLinks} {PreviousPageLink} {FirstPageLink}'}"
>
<p:ajax event="rowSelectRadio"
update=":bus_info_form:bus_info_tbl"/>
<f:facet name="header" id="header">
#{msgs.buses}
</f:facet>
<p:column selectionMode="single" style="width:5%"/>
<p:column headerText="#{msgs.bus_id}"
style="width:15%"
sortBy="#{busesInfo.busID}">
<h:outputText value="#{busesInfo.busID}"/>
</p:column>
<p:column headerText="#{msgs.driver_id}"
style="width:15%"
sortBy="#{busesInfo.driverID}">
<h:outputText value="#{busesInfo.driverID}"/>
</p:column>
<p:column headerText="#{msgs.departure_time}"
style="width:15%"
sortBy="#{busesInfo.departureTime}">
<h:outputText value="#{busesInfo.departureTime}"/>
</p:column>
<p:column headerText="#{msgs.arrival_time}"
style="width:15%"
sortBy="#{busesInfo.arrivalTime}">
<h:outputText value="#{busesInfo.arrivalTime}"/>
</p:column>
<p:column headerText="#{msgs.route}"
style="width:20%"
filterBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"
filterMatchMode="contains"
sortBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}">
<h:outputText value="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"/>
</p:column>
<p:column headerText="#{msgs.license_plate}"
style="width:15%"
sortBy="#{busesInfo.licensePlate}">
<h:outputText value="#{busesInfo.licensePlate}"/>
</p:column>
<p:column headerText="#{msgs.capacity}"
style="width:15%"
sortBy="#{busesInfo.capacity}">
<h:outputText value="#{busesInfo.capacity}"/>
</p:column>
</p:dataTable>
</h:form>
</ui:decorate>
</div>
</h:body>
</html>
I took the sample code from How to create custom components in JavaFX 2.0 using FXML?. the code working fine in jdk7 but the checkbox and combo box values are not working in jdk8. I am not able to click the check box even and select the dropdown.
Please guide me for the same.
Please find the sample code below
Package structure
com.example.javafx.choice
ChoiceCell.java
ChoiceController.java
ChoiceModel.java
ChoiceView.fxml
com.example.javafx.mvc
FxmlMvcPatternDemo.java
MainController.java
MainView.fxml
MainView.properties
ChoiceCell.java
package com.example.javafx.choice;
import java.io.IOException;
import java.net.URL;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
public class ChoiceCell extends ListCell<ChoiceModel>
{
#Override
protected void updateItem(ChoiceModel model, boolean bln)
{
super.updateItem(model, bln);
if(model != null)
{
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try
{
Node root = (Node)fxmlLoader.load(location.openStream());
ChoiceController controller = (ChoiceController)fxmlLoader.getController();
controller.setModel(model);
setGraphic(root);
}
catch(IOException ioe)
{
throw new IllegalStateException(ioe);
}
}
}
}
ChoiceController.java
package com.example.javafx.choice;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
public class ChoiceController
{
private final ChangeListener<String> LABEL_CHANGE_LISTENER = new ChangeListener<String>()
{
public void changed(ObservableValue<? extends String> property, String oldValue, String newValue)
{
updateLabelView(newValue);
}
};
private final ChangeListener<Boolean> IS_SELECTED_CHANGE_LISTENER = new ChangeListener<Boolean>()
{
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue)
{
updateIsSelectedView(newValue);
}
};
private final ChangeListener<Boolean> IS_VISIBILITY1_CHANGE_LISTENER = new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue) {
updateIsVisibleView1(newValue);
}};
#FXML
private Label labelView;
#FXML
private CheckBox isSelectedView;
#FXML
ComboBox isVisible1;
private ChoiceModel model;
public ChoiceModel getModel()
{
return model;
}
public void setModel(ChoiceModel model)
{
if(this.model != null)
removeModelListeners();
this.model = model;
setupModelListeners();
updateView();
}
private void removeModelListeners()
{
model.labelProperty().removeListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().removeListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().removeListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().unbindBidirectional(model.isSelectedProperty());
}
private void setupModelListeners()
{
model.labelProperty().addListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().addListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().addListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().bindBidirectional(model.isSelectedProperty());
}
private void updateView()
{
updateLabelView();
updateIsSelectedView();
updateIsVisibleView1();
}
private void updateLabelView(){ updateLabelView(model.getLabel()); }
private void updateLabelView(String newValue)
{
labelView.setText(newValue);
}
private void updateIsSelectedView(){ updateIsSelectedView(model.isSelected()); }
private void updateIsSelectedView(boolean newValue)
{
isSelectedView.setSelected(newValue);
}
private void updateIsVisibleView1() {
updateIsVisibleView1(model.isVisible1());
}
private void updateIsVisibleView1(boolean newValue) {
isVisible1.setVisible(newValue);
}
}
ChoiceModel.java
package com.example.javafx.choice;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ChoiceModel
{
private final StringProperty label;
private final BooleanProperty isSelected;
private final BooleanProperty isVisible1;
public ChoiceModel(String label, boolean isSelected, boolean isVisible1)
{
this.label = new SimpleStringProperty(label);
this.isSelected = new SimpleBooleanProperty(isSelected);
this.isVisible1 = new SimpleBooleanProperty(isVisible1);
}
public String getLabel(){ return label.get(); }
public void setLabel(String label){ this.label.set(label); }
public StringProperty labelProperty(){ return label; }
public boolean isSelected(){ return isSelected.get(); }
public void setSelected(boolean isSelected){ this.isSelected.set(isSelected); }
public BooleanProperty isSelectedProperty(){ return isSelected; }
public boolean isVisible1()
{
return isVisible1.get();
}
public void setVisible1(boolean isVisible1)
{
this.isVisible1.set(isVisible1);
}
public BooleanProperty isVisibleProperty1()
{
return isVisible1;
}
}
ChoiceView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.example.javafx.choice.ChoiceController">
<children>
<CheckBox fx:id="isSelectedView" />
<Label fx:id="labelView" />
<ComboBox id="isVisible1" fx:id="isVisible1" value="last 7 digits" visible="false">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="last 10 digits" />
<String fx:value="last 9 digits" />
<String fx:value="last 8 digits" />
<String fx:value="last 7 digits" />
<String fx:value="last 6 digits" />
<String fx:value="last 5 digits" />
<String fx:value="last 4 digits" />
<String fx:value="last 3 digits" />
</FXCollections>
</items>
</ComboBox>
</children>
</HBox>
FxmlMvcPatternDemo.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceController;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FxmlMvcPatternDemo extends Application
{
public static void main(String[] args) throws ClassNotFoundException
{
Application.launch(FxmlMvcPatternDemo.class, args);
}
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load
(
FxmlMvcPatternDemo.class.getResource("MainView.fxml"),
ResourceBundle.getBundle(FxmlMvcPatternDemo.class.getPackage().getName()+".MainView")/*properties file*/
);
ChoiceController controller = new ChoiceController();
stage.setScene(new Scene(root));
stage.show();
}
}
MainController.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceCell;
import com.example.javafx.choice.ChoiceModel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
public class MainController implements Initializable
{
#FXML
private ListView<ChoiceModel> choicesView;
#Override
public void initialize(URL url, ResourceBundle rb)
{
choicesView.setCellFactory(new Callback<ListView<ChoiceModel>, ListCell<ChoiceModel>>()
{
public ListCell<ChoiceModel> call(ListView<ChoiceModel> p)
{
return new ChoiceCell();
}
});
choicesView.setItems(FXCollections.observableArrayList
(
new ChoiceModel("Tiger", true, false),
new ChoiceModel("Shark", false, true),
new ChoiceModel("Bear", false, true),
new ChoiceModel("Wolf", true, true)
));
}
#FXML
private void handleForceChange(ActionEvent event)
{
if(choicesView != null && choicesView.getItems().size() > 0)
{
boolean isSelected = choicesView.getItems().get(0).isSelected();
choicesView.getItems().get(0).setSelected(!isSelected);
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.mvc.MainController"
prefWidth="300"
prefHeight="400"
fillWidth="false"
>
<children>
<Label text="%title" />
<ListView fx:id="choicesView" />
<Button text="Force Change" onAction="#handleForceChange" />
</children>
</VBox>
MainView.proprties
title=JavaFX 2.0 FXML MVC demo
I didn't dig deeper but refactoring like as following should suffice. Double check for correct executions of attached and removed listeners.
public class ChoiceCell extends ListCell<ChoiceModel> {
private Node root;
private ChoiceController controller;
public ChoiceCell() {
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try {
root = (Node) fxmlLoader.load(location.openStream());
controller = (ChoiceController) fxmlLoader.getController();
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
#Override
protected void updateItem(ChoiceModel model, boolean bln) {
super.updateItem(model, bln);
if (model != null) {
controller.setModel(model);
setGraphic(root);
} else {
setGraphic(null);
}
}
}
I have just recently started learning Tapestry, trying to make my own Celebrity Collector application.
Everything worked fine, until I wanted to provide a database support instead of mocked database.
I'm using Hibernate 3.6 with Tapestry 5.3.7.
I have configured my database like this:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:target\database</property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa</property>
<property name="hbm2ddl.auto">create-drop</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
</session-factory>
</hibernate-configuration>
My DAO interface and implementation looks like this:
package com.example.addressbook.data;
import java.util.List;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.PostInjection;
import com.example.addressbook.entities.Celebrity;
public interface CelebrityDao {
#CommitAfter
int count();
#CommitAfter
void add(Celebrity celebrity);
#CommitAfter
Celebrity get(long id);
#CommitAfter
List<Celebrity> getAll();
#CommitAfter
List<Celebrity> getRange(long startIndex, long endIndex);
#PostInjection
void prepare();
}
package com.example.addressbook.data.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import com.example.addressbook.data.CelebrityDao;
import com.example.addressbook.entities.Celebrity;
public class CelebrityDaoImpl implements CelebrityDao {
#Inject
protected Session session;
public void add(Celebrity celebrity) {
session.persist(celebrity);
}
public Celebrity get(long id) {
Criteria criteria = session.createCriteria(Celebrity.class);
criteria.add(Restrictions.eq("id", id));
Celebrity celebrity = (Celebrity) criteria.uniqueResult();
return celebrity;
}
public List<Celebrity> getAll() {
Criteria criteria = session.createCriteria(Celebrity.class);
List rawResults = criteria.list();
List<Celebrity> results = new ArrayList<Celebrity>();
for (Object object : rawResults) {
results.add((Celebrity) object);
}
return results;
}
public List<Celebrity> getRange(long startIndex, long endIndex) {
Criteria criteria = session.createCriteria(Celebrity.class);
criteria.add(Restrictions.between("id", startIndex, endIndex));
List rawResults = criteria.list();
List<Celebrity> results = new ArrayList<Celebrity>();
for (Object object : rawResults) {
results.add((Celebrity) object);
}
return results;
}
public void prepare() {
// adding some initial records in the database
}
public int count() {
return getAll().size();
}
}
My ShowAll class is here:
package com.example.addressbook.pages;
import java.text.Format;
import java.util.List;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.grid.GridDataSource;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;
import com.example.addressbook.data.CelebrityDao;
import com.example.addressbook.entities.Celebrity;
import com.example.addressbook.model.User;
import com.example.addressbook.util.CelebrityEncoder;
import com.example.addressbook.util.CelebritySelectModel;
import com.example.addressbook.util.Formats;
import com.example.addressbook.util.HibernateEntityDataSource;
public class ShowAll {
#SessionState
private User user;
private boolean userExists;
#Inject
private CelebrityDao dao;
#InjectPage
private Details detailsPage;
#Property
private Celebrity celebrity;
#Inject
private BeanModelSource beanModelSource;
#Inject
private Messages messages;
String onActivate() {
if (!userExists)
return "Index";
return null;
}
#OnEvent(component = "detailsLink")
Object onShowDetails(long id) {
Celebrity celebrity = dao.get(id);
detailsPage.setCelebrity(celebrity);
System.err.println("Requested ID: " + id);
System.err.println("Result: " + celebrity.getLastName());
return detailsPage;
}
public BeanModel<Celebrity> getModel() {
return beanModelSource.createDisplayModel(Celebrity.class, messages);
}
public List<Celebrity> getAllCelebrities() {
return this.dao.getAll();
}
public Format getDateFormat() {
return Formats.getDateFormat();
}
public User getUser() {
return user;
}
public GridDataSource getCelebritySource() {
return new HibernateEntityDataSource<Celebrity>(Celebrity.class, dao);
}
public SelectModel getCelebrityModel() {
return new CelebritySelectModel(getAllCelebrities());
}
public ValueEncoder<Celebrity> getCelebrityEncoder() {
return new CelebrityEncoder(dao);
}
#Persist
private Celebrity selectedCelebrity;
public Celebrity getSelectedCelebrity() {
return selectedCelebrity;
}
public void setSelectedCelebrity(Celebrity selectedCelebrity) {
this.selectedCelebrity = selectedCelebrity;
}
public String getSelectedCelebrityName() {
if (selectedCelebrity == null) {
return "";
}
return selectedCelebrity.getFirstName() + " " + selectedCelebrity.getLastName();
}
}
And here is how I add new ones:
package com.example.addressbook.pages;
import org.apache.tapestry5.ioc.annotations.Inject;
import com.example.addressbook.data.CelebrityDao;
import com.example.addressbook.entities.Celebrity;
public class AddCelebrity {
private Celebrity celebrity;
#Inject
private CelebrityDao dao;
public void onActivate() {
System.out.println("OnActivate: " + dao.getAll().toString());
if (celebrity == null) {
celebrity = new Celebrity();
}
}
public Celebrity getCelebrity() {
return celebrity;
}
public void setCelebrity(Celebrity celebrity) {
this.celebrity = celebrity;
}
Object onSuccess() {
dao.add(celebrity);
System.out.println("All celebrities: " + dao.getAll().toString());
return ShowAll.class;
}
}
The problem is the following:
When I first come to ShowAll page, my records are pulled from the database and rendered.
When I refresh the page, the records are removed magically and nothing is displayed. The database is empty (dao.getAll() returns and empty list)
When I add a new Celebrity via AddCelebrity page, it is inserted into the database, but as the page is refreshed, the magic happens again and the database is empty again.
I have binded my DAO interface and implementation in AppModule class:
public static void bind(ServiceBinder binder) {
binder.bind(SupportedLocales.class, SupportedLocalesImpl.class);
binder.bind(CelebrityDao.class, CelebrityDaoImpl.class);
}
HELP!! :)
The answer was to add another method to AppModule class
#Match("*Dao")
public static void adviseTransactions(HibernateTransactionAdvisor advisor,
MethodAdviceReceiver receiver) {
advisor.addTransactionCommitAdvice(receiver);
}
So that Tapestry could actually do something with #CommitAfter annotation on my DAO methods.