In JavaFX how to add combobox with data in table view - mysql

I have tried a lot but not able to populate all values in the data base into my combo box table cell.
Controller.java
public class controller {
GetConnection gc = new GetConnection();
PreparedStatement pst;
ResultSet rs;
Statement st;
private ObservableList<Users> datas = FXCollections.observableArrayList();
public controller() {
}
#FXML
private TableView<Users> table;
#FXML
private TableColumn<Users, String> c1;
#FXML
private void editable() {
List<String> names = new ArrayList<String>();
try {
ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode")));
}
for (String name : names) {
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(name));
//not getting full items here
System.out.println("hell3" + name);// am getting full items here
}
table.setItems(null);
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class Users {
private StringProperty Itemc;
private Users(String Itemc) {
this.Itemc = new SimpleStringProperty(Itemc);
}
public String getItemc() {
return Itemc.get();
}
public void setItemc(String Itemc) {
this.Itemc.set(Itemc);
}
public StringProperty ItemcProperty() {
return Itemc;
}
}
}
table.fxml
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication47.controller">
<children>
<TableView fx:id="table" editable="true" layoutX="136.0" layoutY="58.0" onKeyPressed="#editable" prefHeight="200.0" prefWidth="335.0">
<columns>
<TableColumn fx:id="c1" prefWidth="333.0" text="Name" />
</columns>
</TableView>
</children>
</AnchorPane>
Main.java loader
public class Tableveiw extends Application {
private Stage primaryStage;
private AnchorPane pane;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
showPerson();
}
public void showPerson() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Tableveiw.class.getResource("table.fxml"));
pane = (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
Database Connection
public class GetConnection {
public Connection getConnection() throws Exception {
Connection con = null;
try {
System.out.println("MySQL Connect Example.");
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
// Accessing driver from the jar file
Class.forName(driver).newInstance();
// Creating a veriable for Connection Called conn
con = DriverManager.getConnection(url + dbName, "root", "");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String arg[]) {
GetConnection con = new GetConnection();
System.out.println("Connection" + con);
}
}
My problem with the code is that am not getting the full items in the database record to my c1 combobox table cell.Am only getting the last items of the database record in my comboboxtablecell.I have created array but still not helping .Why am not able to populate whole items in database into my combobox tablecell .Please help me with neccessary changes in the code.

This is Just basic functionality . when you duble click on cell combobox will visible then you can select value.to see direct Combobox you have write own TableCell class see this you ll understand. I hope this will help you. any ?s post a comment
private void editable() {
try {
ObservableList<String> names = FXCollections.observableArrayList();
ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode")));
}
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(name));
table.setEditable(true);
table.getItems().clear();
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}

Related

Could not load type 'Devart.Data.MySql.MySqlDependency' from assembly 'Devart.Data.MySql

When I run my code, there is an error as below:
Could not load type 'Devart.Data.MySql.MySqlDependency' from assembly
'Devart.Data.MySql, Version=8.10.1086.0, Culture=neutral,
PublicKeyToken=09af7300eec23701'.
Which part would cause this problem?
Here is my sample codes...
using Devart.Data.MySql;
public partial class Form1 : Form
{
public string Query = "Select * from tbltransaction";
public MySql.Data.MySqlClient.MySqlConnection cn;
public MySql.Data.MySqlClient.MySqlDataAdapter sqlAdapter;
public DataSet dsdatagrid;
public DataTable dt;
public DataGridView datagrid;
public Form1()
{
InitializeComponent();
Start();
}
string connectionString = "User Id=root;Password=123!##abcD;Host=localhost;Database=kcms1_test;";
void Start()
{
try
{
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
MySqlCommand commandDeptEmp = new MySqlCommand("select * from tbltransaction", connection);
//MySqlCommand commandPict = new MySqlCommand("select * from mysqlnet_pictures", connection);
MySqlDependency dependency = new MySqlDependency(commandDeptEmp, 1000);
dependency.AddCommandDependency(commandDeptEmp);
//dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
MySqlDependency.Stop(connectionString);
MySqlDependency.Start(connectionString);
OpenLocalDBConnection();
View_Data();
DataGridView_tbltransaction.DataSource = datagrid.DataSource;
}
catch
{
Stop();
}
finally
{
}
}
void Stop()
{
MySqlDependency.Stop(connectionString);
}
void dependency_OnChange(object sender, MySqlTableChangeEventArgs e)
{
// process changes
View_Data();
DataGridView_tbltransaction.DataSource = datagrid.DataSource;
}
void View_Data()
{
sqlAdapter = new MySql.Data.MySqlClient.MySqlDataAdapter(Query, cn);
dsdatagrid = new DataSet();
sqlAdapter.Fill(dsdatagrid);
dt = new DataTable();
datagrid.DataSource = dsdatagrid.Tables;
}
void OpenLocalDBConnection()
{
cn.ConnectionString = "server=locahost;userid=root;password=123!##abcD;database=kcms1_test";
cn.Open();
}
}

Search Result in new Window (JavaFx)

I am currently working on a software module consisting of searching in a database using JavaFx.
Everything is working as expected.
But the only problem is that in my result table I am showing only few details of search (from UX issues: I have too much details and long texts).
What I would like to do is to show a new window with all details of a clicked row in TextFields and TextArea.
I looked at several tutorials and answers, but unfortunately nothing is working.
Any help would be appreciated!
Thank you.
SearchResult.setOnMouseClicked(new EventHandler<MouseEvent>() {
Gemo temp;
#Override
public void handle(MouseEvent event) {
Gemo row = SearchResult.getSelectionModel().getSelectedItem();
if(row == null) {
System.out.print("I am not in");
return ;
}
else {
temp = row;
String id = String.format(temp.getRef());
System.out.println(id);
FXMLLoader loader=new FXMLLoader();
loader.setLocation(getClass().getResource("DetailsWindow.fxml"));
ControllerDetails gemodetails=loader.getController();
ControllerDetails gd=new ControllerDetails();
gd.SearchById(id);
try{
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
Parent p= loader.getRoot();
Stage stage=new Stage();
stage.setTitle("More Details");
stage.setScene(new Scene(p));
stage.show();
}
}
});
public class ControllerDetails {
#FXML
private TextField fn_patient;
#FXML
private TextField ln_patient;
#FXML
private TextField db_patient;
#FXML
private TextField id_patient;
#FXML
private TextField id_visit;
#FXML
private TextField date_visit;
#FXML
private TextField fn_user;
#FXML
private TextField ln_user;
#FXML
private TextField status;
#FXML
private TextArea com;
#FXML
public void initialize(){
}
public void SearchById(String id) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
connection = ConnectionConfiguration.getConnection();
statement = connection.prepareStatement("my_sql_query");
rs = statement.executeQuery();
while (rs.next()) {
id_visit.setText(rs.getString(1));
id_patient.setText(rs.getString(2));
date_visit.setText(rs.getString(3));
com.setText(rs.getString(4));
fn_patient.setText(rs.getString(5));
ln_patient.setText(rs.getString(6));
db_patient.setText(rs.getString(7));
fn_user.setText(rs.getString(8));
ln_user.setText(rs.getString(9));
status.setText(rs.getString(10));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try to create a simple fxml file with a listView. Place the data you are interested in into this listView. If you prefer something else than listView, that's ok too.
To open such fxml in a new window try something like that:
Stage s = new Stage();
try {
s.setScene(new Scene(new FXMLLoader(getClass().getResource("your_fxml_name")).load()));
s.show();
} catch (IOException e) {
e.printStackTrace();
}
You have two action options: either extract all the data and paste it into a table, or extract a small part that you put in a table, and extract the extra on demand (display details).
The example I give is not addicted to the approach - it simply tells how to transfer table data (a selected row) to a dialog (its controller)
public class Controller {
#FXML
private TableView<MySearchResult> tableView;
#FXML
private void initialize() {
tableView.setItems(new Database().serach("query", "query"));
tableView.setOnMouseClicked(event -> {
if(event.getClickCount() == 2) {
showDetailsDialog();
}
});
}
private void showDetailsDialog() {
MySearchResult result = tableView.getSelectionModel().getSelectedItem();
if(result == null) {
return;
}
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("details_dilaog.fxml"));
Dialog dlg = new Dialog();
dlg.initOwner(tableView.getScene().getWindow());
dlg.initModality(Modality.APPLICATION_MODAL);
dlg.getDialogPane().setContent((Parent) loader.load());
dlg.getDialogPane().getButtonTypes().setAll(ButtonType.OK);
DetailsDialogControler ddc = loader.getController();
ddc.showDetailsFor(result);
dlg.showAndWait();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My goal is to show the logic in the showDetailsDialog() function.

JavaFx combobox from mysql

Good Day I am completely new to coding. I am building an app which uses a combobox besides other library items. The problem I am facing is that while attempting to populate combobox items from a Mysql Db the item values get duplicated each time the drop down is clicked.
How I can keep this from happening ? I do understand that my approach itself could be erroneous.
#FXML
public void getStation() {
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
comboBoxStation.getItems().add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
Ok so I moved the function to the initialize() method in the controller and created an Observabale list called station
private ObservableList<String> stationsList = FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle rb) {
//
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
stationsList.add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
and then left only this line in the original function....seems to be working.
#FXML
private void getStation() {
comboBoxStation.setItems(stationsList);
}

How to view generated PDF from JapserReport to Primefaces Media Component?

I have the following Method that generates My PDF from Jasper as byte[].
#Named
#ViewScoped
public class ReportingBean extends BasicBean {
...
public void generateUebersichtMaterial() throws FileNotFoundException {
InputStream pathMaster_jrxml;
InputStream pathSubReport_jrxml;
pathMaster_jrxml = getClass().getResourceAsStream("/reports/mainreport.jrxml");
pathSubReport_jrxml = getClass().getResourceAsStream("/reports/subreport.jrxml");
try {
getConnection();
HashMap<String, Object> params = new HashMap<>();
List<ReportMaterialUebersicht> list = new ArrayList<>();
list = reportFacade.getReportMaterialUebersicht();
JasperReport subreport = JasperCompileManager.compileReport(pathSubReport_jrxml);
JasperReport report = JasperCompileManager.compileReport(pathMaster_jrxml);
params.put(JRParameter.REPORT_LOCALE, Locale.FRENCH);
params.put("subReport", subreport);
JasperPrint jasperPrint = JasperFillManager.fillReport(report, params,
new JRBeanArrayDataSource(list.toArray()));
connection.close();
content = JasperExportManager.exportReportToPdf(jasperPrint);
Faces.sendFile(content, "Materialuebersicht.pdf", false);
} catch (Exception e) {
Logger.getLogger(ReportingBean.class.getName()).log(Level.SEVERE, null, e);
}
}
...
}
Instead of open the PDF in a new window I want to use the primefaces media component like:
<p:media value="#{reportingBean.myPDF}" width="100%" height="100%" player="pdf" />
How can this be done?
I´ve tried it out, and I found out the solution by myself by using the StreamedContent from Primefaces.
Added these two lines to the ReportBean:
InputStream in = new ByteArrayInputStream(content);
myDoc = new DefaultStreamedContent(in, "application/pdf", "test.pdf");
In the PostConstruct of the Bean I initilize the variable myPDF and call it from the media component.
<p:media value="#{reportingBean.myPDF}" width="100%" height="100%" player="pdf" />
Here is the full Bean example:
The ReportingBean:
#Named
#ViewScoped
public class ReportingBean extends BasicBean {
...
private DefaultStreamedContent myPDF;
public void generateUebersichtMaterial() throws FileNotFoundException {
InputStream pathMaster_jrxml;
InputStream pathSubReport_jrxml;
pathMaster_jrxml = getClass().getResourceAsStream("/reports/mainreport.jrxml");
pathSubReport_jrxml = getClass().getResourceAsStream("/reports/subreport.jrxml");
try {
getConnection();
HashMap<String, Object> params = new HashMap<>();
List<ReportMaterialUebersicht> list = new ArrayList<>();
list = reportFacade.getReportMaterialUebersicht();
JasperReport subreport = JasperCompileManager.compileReport(pathSubReport_jrxml);
JasperReport report = JasperCompileManager.compileReport(pathMaster_jrxml);
params.put(JRParameter.REPORT_LOCALE, Locale.FRENCH);
params.put("subReport", subreport);
JasperPrint jasperPrint = JasperFillManager.fillReport(report, params,
new JRBeanArrayDataSource(list.toArray()));
connection.close();
content = JasperExportManager.exportReportToPdf(jasperPrint);
Faces.sendFile(content, "Materialuebersicht.pdf", false);
} catch (Exception e) {
Logger.getLogger(ReportingBean.class.getName()).log(Level.SEVERE, null, e);
}
}
...
#PostConstruct
private void init() {
try {
materialUebersichtPDF = generateUebersichtMaterial();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

JavaFX, SceneBuilder, Populating TableView with MySQL Result Set

I have finally overcome my issue with a NPE in my code whilst learning FX/FXML. I now however have a different problem, a window opens with my TableView however there is no content in the table at all. As you cann I have printed out the JobList to make sure there is content being returned, and this returns three jobs (the correct amount). Am I missing something that binds the table to the returned list?
Here is the code;
public class SecondInterface implements Initializable {
private JobDataAccessor jAccessor;
private String aQuery = "SELECT * FROM progdb.adamJobs";
private Parent layout;
private Connection connection;
#FXML
TableView<Job> tView;
public void newI(Connection connection) throws Exception {
Stage primaryStage;
primaryStage = MainApp.primaryStage;
this.connection = connection;
System.out.println(connection);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Test1.fxml"));
fxmlLoader.setController(this);
try {
layout = (Parent) fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
primaryStage.getScene().setRoot(layout);
}
public Parent getLayout() {
return layout;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
jAccessor = new JobDataAccessor();
try {
System.out.println("This connection: " + connection);
System.out.println("This query: " + aQuery);
List<Job> jList = jAccessor.getJobList(connection, aQuery);
for (Job j : jList) {
System.out.println(j);
}
tView.getItems().addAll(jAccessor.getJobList(connection, aQuery));
} catch (SQLException e) {
e.printStackTrace();
}
}
}