I am creating javafx application where I insert selected items of combobox which are also populated from database to another table of database but problem is that combobox's selection model is not working consistent some time it is giving item which are selected but some it sends null value to database
Code:
package application;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import org.controlsfx.control.textfield.TextFields;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
public class EntryFormController implements Initializable {
Connection connection = SqliteConnection.Connector();
PreparedStatement preparedStatement = null;
ResultSet rs = null;
ObservableList<String> cBoxList1 = FXCollections.observableArrayList();
ObservableList<String> cBoxList2 = FXCollections.observableArrayList();
#FXML
private ComboBox<String> TruckNo;
#FXML
private ComboBox<String> exp1;
#FXML
private ComboBox<String> exp2;
#FXML
private void addButton(ActionEvent e) {
String query = "insert into entry (Truck,Expense)values(?,?),(?,?) ";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString
(2,TruckNo.getSelectionModel().getSelectedItem());
preparedStatement.setString
(3, exp1.getSelectionModel().getSelectedItem());
TruckNo.getSelectionModel().getSelectedItem());
preparedStatement.setString
(9,exp2.getSelectionModel().getSelectedItem());
preparedStatement.execute();
TruckNo.setValue(null);
TruckNo.valueProperty().set(null);
exp1.setValue(null);
exp1.valueProperty().set(null);
exp2.setValue(null);
exp2.valueProperty().set(null);
preparedStatement.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
exp1.setItems(cBoxList1);
exp1.setEditable(true);
loadDatabaseDataCombo1();
exp2.setItems(cBoxList2);
exp2.setEditable(true);
TruckNo.setItems(trkList);
TruckNo.setEditable(true);
loadDatabaseDataCombo6();
TextFields.bindAutoCompletion(exp1.getEditor(), exp1.getItems());
TextFields.bindAutoCompletion(exp2.getEditor(), exp2.getItems());
TextFields.bindAutoCompletion(TruckNo.getEditor(),TruckNo.getItems());
}
private void loadDatabaseDataCombo6() {
String query = "select * from Truck";
try {
preparedStatement = connection.prepareStatement(query);
rs = preparedStatement.executeQuery();
while (rs.next()) {
trkList.add(rs.getString("TruckNo"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private void loadDatabaseDataCombo2() {
String query = "select * from Expense";
try {
preparedStatement = connection.prepareStatement(query);
rs = preparedStatement.executeQuery();
while (rs.next()) {
cBoxList2.add(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void loadDatabaseDataCombo1() {
String query = "select * from Expense";
try {
preparedStatement = connection.prepareStatement(query);
rs = preparedStatement.executeQuery();
while (rs.next()) {
cBoxList1.add(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Related
I would like to retrieve a value in a combobox which is of type int in order to perform an insert in an sql table thanks to a query. However, I can't do it, does anyone have a solution?
Here is my ComboBox and I try to get the value in "DBUtils.ajouterPersonnelMembre" :
package eu.hautil.pigeonnier;
import java.net.URL;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
public class APMCheckBoxController implements Initializable {
#FXML
private ComboBox id_role;
#FXML
private TextField nom;
#FXML
private TextField prenom;
#FXML
final DatePicker date_arrivee = new DatePicker(LocalDate.now());
#FXML
final DatePicker date_depart = new DatePicker(LocalDate.now());
/*final DatePicker date_depart = new DatePicker(LocalDate.now());
Instant instant_depart = date_depart.toInstant();
LocalDate localDateDepart = instant_depart.atZone(ZoneId.systemDefault()).toLocalDate();*/
#FXML
private Button submit_button;
// Drop Down Menu
#Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList<Integer> list = FXCollections.observableArrayList(1, 2, 3, 4, 5, 6);
id_role.setItems(list);
// End of the Drop Down Menu
submit_button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
DBUtils.ajouterPersonnelMembre(event, id_role.getItems(), nom.getText(), prenom.getText(), date_arrivee, date_depart);
}
});
}
}
And my function "ajouterPersonnelMembre" :
public static void ajouterPersonnelMembre(ActionEvent event, int id_role, String nom, String prenom, DatePicker date_arrivee, DatePicker date_depart) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/le_pigeonnier", "root", "root");
preparedStatement = connection.prepareStatement("INSERT INTO personnel(id_role, nom, prenom, date_arrivee, date_depart) VALUES (?,?,?,?,?)");
preparedStatement.setInt(1, id_role);
preparedStatement.setString(2, nom);
preparedStatement.setString(3, prenom);
preparedStatement.setDate(4, date_arrivee);
preparedStatement.setDate(5, date_depart);
resultSet = preparedStatement.executeQuery();
if(resultSet != null){
System.out.println("Membre du personel bien ajouté !");
changeScene(event, "/fxml/menu.fxml", "", "");
resultSet.close();
} else{
System.out.println("Une erreur est survenue, le membre du personnel n'a pas pu être ajouté");
changeScene(event, "/fxml/sample.fxml", "", "");
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
Thanks in advance ;)
Make sure you use the generics not the raw type:
Instead of:
#FXML
private ComboBox id_role;
use
#FXML
private ComboBox<Integer> id_role;
or better when following the Java naming conventions:
use
#FXML
private ComboBox<Integer> idRole;
and likely you want to call something like idRole.getValue() instead of idRole.getItems().
I hope you can help me. I'm trying to round a image retrieved from my database. In the next image you can see the image is correctly displayed in a imageview. User selects a new item in the table and the image change to display the correct image, this is working, no problems here.
This is the program
I try with this code in the gestionarEventos :
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
Image im = imgfotovisi.getImage();
circulo.setFill(new ImagePattern(im));
But java say :
... 58 more
Caused by: java.lang.NullPointerException: Image must be non-null.
at javafx.scene.paint.ImagePattern.<init>(ImagePattern.java:235)
The program runs if I delete the lines below the
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
line.
When it runs, I don't know why says the image is null, when I can see clearly there.
This is ver_visitantes class:
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.InputEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class ver_visitantes implements Initializable {
#FXML private TableView<visitantes> tbvisitantes;
#FXML private TableColumn<visitantes, String> clcedula,clnombres,clapellidos,clapartamento,clcelular,clobservaciones;
#FXML private ImageView imgfotovisiact,imgfotoact,imgfotovisi,imgfoto;
#FXML private TextField txtcedula,txtnombres,txtapto,txtapellidos,txtapt,txtcelular,txtobservaciones;
#FXML private Label lblinfovisiact,lblusuario,lblstatusvisi;
#FXML private Circle circulo;
private ObservableList<visitantes> visitorlist;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
ConexionSQL cnt = new ConexionSQL();
cnt.conexion();
visitorlist = FXCollections.observableArrayList();
visitantes.llenarlistavisitas(cnt.conexion(), visitorlist);
tbvisitantes.setItems(visitorlist);// llenar table view con la lista
clcedula.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcedula()));
clnombres.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getnombres()));
clapellidos.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapellidos()));
clapartamento.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapartamento()));
clcelular.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcelular()));
clobservaciones.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getobservaciones()));
gestionarEventos();
tbvisitantes.getSelectionModel().selectFirst();
}
public void gestionarEventos() {
tbvisitantes.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<visitantes>() {
#Override
public void changed(ObservableValue<? extends visitantes> arg0, visitantes valorAnterior,
visitantes valorSeleccionado) {
imgfoto.setVisible(false);
btnmodificar.setDisable(false);
btncancelar.setDisable(false);
btneliminar.setDisable(false);
imageRetrievalService.restart();
if (valorSeleccionado != null) {
txtcedula.setText(String.valueOf(valorSeleccionado.getcedula()));
txtnombres.setText(valorSeleccionado.getnombres());
txtapellidos.setText(valorSeleccionado.getapellidos());
txtapto.setText(String.valueOf(valorSeleccionado.getapartamento()));
txtcelular.setText(String.valueOf(valorSeleccionado.getcelular()));
txtobservaciones.setText(String.valueOf(valorSeleccionado.getobservaciones()));
}
}
});
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
}
private final Service<Image> imageRetrievalService = new Service<Image>() {// cargar imagen en visitantes
#Override
protected Task<Image> createTask() {
final String id;
final visitantes visitante = tbvisitantes.getSelectionModel().getSelectedItem();
if (visitante == null) {
id = null;
} else {
id = visitante.getcedula();
}
return new Task<Image>() {
#Override
protected Image call() throws Exception {
if (id == null) {
return null;
}
return visitante.getImageById(id);
}
};
}
};
}
this is the visitantes class,called from the imageRetrievalService to get the image:
package application;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.image.Image;
public class visitantes {
private StringProperty cedula;
private StringProperty nombres;
private StringProperty apellidos;
private StringProperty apartamento;
private StringProperty celular;
private StringProperty observaciones;
public visitantes(String cedula,String nombres,String apellidos,String apartamento,String celular,String observaciones){
this.cedula = new SimpleStringProperty(cedula);
this.nombres = new SimpleStringProperty(nombres);
this.apellidos = new SimpleStringProperty(apellidos);
this.apartamento = new SimpleStringProperty(apartamento);
this.celular = new SimpleStringProperty(celular);
this.observaciones = new SimpleStringProperty(observaciones);
}
public String getnombres(){
return nombres.get();
}
public void setnombres(String nombres){
this.nombres = new SimpleStringProperty(nombres);
}
public String getcedula(){
return cedula.get();
}
public void setcedula(String cedula){
this.cedula = new SimpleStringProperty(cedula);
}
public String getapellidos(){
return apellidos.get();
}
public void setapellidos(String apellidos){
this.apellidos = new SimpleStringProperty(apellidos);
}
public String getapartamento(){
return apartamento.get();
}
public void setapartamento(String apartamento){
this.apartamento = new SimpleStringProperty(apartamento);
}
public String getcelular(){
return celular.get();
}
public void setcelular(String celular){
this.celular = new SimpleStringProperty(celular);
}
public Image getImageById(String id) throws SQLException, IOException {
try (
ConexionSQL cn = new ConexionSQL();
Connection con = cn.conexion();
PreparedStatement ps = con.prepareStatement(
"SELECT foto_visi FROM visitantes WHERE cedula_visi = ?");
) {
ps.setString(1, id);
ResultSet results = ps.executeQuery();
Image img = null ;
if (results.next()) {
Blob foto = results.getBlob("foto_visi");
InputStream is = foto.getBinaryStream();
img = new Image(is) ; // false = no background loading
is.close();
}
results.close();
return img ;
} catch (Throwable e) {
String info = e.getMessage();
System.out.println(info);
}
return null;
}
}
I think the problem is here:
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
I don't know if the retrieved image is loaded in the imageivew in this line. Looks like yes, but if I do
Image im = imgfotovisi.getImage();
Java says it is null. Then I can't get the image into the circle.
Thanks in advance :)
bind isn't going to load an image itself, it will just bind so that one variable will change when the source changes (in this case the value property of the service), which isn't going to happen straight away as the service is running asynchronously. So, if you query the value straight away after issuing the bind statement, you won't get the result you are expecting, as the source hasn't yet changed.
Instead you need to take action only once the image is actually available.
For instance:
imageRetrievalService.valueProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);
Or, if you don't want a direct linkage to the service, and given that the imgfotovsi image property is already bound to the service value:
imgfotovisi.imageProperty().addListener((obs, oldVal, newVal) ->
if (newVal != null)
circulo.setFill(new ImagePattern(newVal))
);
Please help me to add item from addproject controller to project controller. I want to add item from addprojects controller to projectscontroller method. Please guide me to resolve this. please guide to dynamically change the right side split pane view and add tree item in treeview and show to user.
package com.define.controller;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.Event;
//import org.apache.commons.io.FileUtils;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tab;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javax.naming.Context;
import testapp.TestApp;
public class ProjectsController implements Initializable{
// #FXML private HBox fileList;
#FXML TreeView<String> Maintree ;
#FXML private AnchorPane Anchorpane;
File destinationFolder;
//Image img = new Image();
//private final Node rootIcon = new ImageView(img);
/* private final Node rootIcon = new ImageView(
new Image(getClass().getResourceAsStream("G:\\workspace\\DefineApp\\src\\images\\folder.png")));*/
File file = new File("D:\\DefineApp\\src\\images\\folder.png");
Image image = new Image(file.toURI().toString(),20,20,false,false);
private Node rootIcon = new ImageView(image);
#Override
public void initialize(URL location, ResourceBundle resources) {
File currentDir = new File("D:\\DefineApp\\src\\Documents"); // current directory
rootItem.setExpanded(true);
Maintree.setShowRoot(false);
Maintree.setRoot(rootItem);
findFiles(currentDir);
try {
changeView();
} catch (IOException ex) {
Logger.getLogger(ProjectsController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void UploadFiles() throws IOException{
DirectoryChooser directory = new DirectoryChooser();
directory.setTitle("Choose Directory");
final File selectedDirectory = directory.showDialog(null);
File sourcefolder = new File(selectedDirectory.getAbsolutePath());
String projectName = "Symbiance";
String studyName = "study1";
destinationFolder = new File("G:\\workspace\\DefineApp\\src\\"+projectName+"\\"+studyName);
if(!destinationFolder.exists()){
destinationFolder.mkdirs();
if(destinationFolder.isDirectory()){
// FileUtils.copyDirectory(sourcefolder, destinationFolder);
System.out.println("Files Copied Successfully");
}
}else{
if(destinationFolder.isDirectory()){
//FileUtils.copyDirectory(sourcefolder, destinationFolder);
System.out.println("Files Copied Successfully");
}
}
//Method call for list the files
listFiles();
}
public void listFiles(){
//fileList.setPadding(new Insets(15, 12, 15, 12));
//fileList.setSpacing(10);
File[] listOfFiles = destinationFolder.listFiles();
CheckBox[] cbs = new CheckBox[listOfFiles.length];
int i=0;
for (File file : listOfFiles) {
CheckBox cbox = cbs[i]= new CheckBox(file.getName());
i++;
}
//fileList.getChildren().addAll(cbs);
}
TreeItem<String> rootItem = new TreeItem<String>("Root");
public void findFiles(File currentDir){
//rootItem.setGraphic(rootIcon);;
TreeItem<String> subfolder;
// parent = new TreeItem<String> (parent.getValue(),rootIcon);
System.out.println("1");
File folder = new File(currentDir.getAbsolutePath());
File[] listOfFiles = folder.listFiles();
for (File file:listOfFiles) {
if(file.isDirectory()){
subfolder = new TreeItem<String> (file.getName());
rootItem.getChildren().add(subfolder);
File subFolderName = new File(file.getAbsolutePath());
File[] subFolderFiles = subFolderName.listFiles();
for(File f:subFolderFiles){
TreeItem<String> it= new TreeItem<String>(f.getName());
subfolder.getChildren().add(it);
}
}
}
}
public void changeView() throws IOException{
System.out.println("change view is called");
Anchorpane.getChildren().add(TestApp.getInstance().designChooser("com/define/views/AddProject.fxml"));
//setContent();
}
public void addProject(String name,Event e){
rootItem.getChildren().add(new TreeItem(name));
System.out.println("test check");
}
}
another controller;
package com.define.controller;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TreeItem;
import javafx.scene.text.Text;
public class AddProjectController implements Initializable{
#FXML Button yesbutton;
#FXML RadioButton projectYesRadio;
#FXML RadioButton projectNORadio;
#FXML TextField projectId;
#FXML TextField projectName;
final ToggleGroup Projectgroup = new ToggleGroup();
final File baseFolder = new File("D:\\DefineApp\\src\\Documents");
File projectFolder;
#Override
public void initialize(URL location, ResourceBundle resources) {
projectYesRadio.setToggleGroup(Projectgroup);
projectNORadio.setToggleGroup(Projectgroup);
projectYesRadio.setSelected(true);
}
public void addProject(ActionEvent e){
projectFolder = new File("D:\\DefineApp\\src\\Documents\\"+projectName.getText());
projectFolder.mkdir();
ProjectsController pt = new ProjectsController();
pt.addProject(projectName.getText(),e);
//System.out.println(projectController.Maintree.getRoot());
//.rootItem.getChildren().add(new TreeItem(projectName.getText()));
//projectController.findFiles(baseFolder);
System.out.println("test check");
}
public void radiocalled(){
//yesbutton.setVisible(false);
}
}
I am trying to populate a TableView called CustomerTableViewusing a ComboBox called ComboBoxSelectCustomer. Basically the user selects a customer from the list of customers inside the ComboBox and than the TableView will populate with data that matches that customer's name. I have multiple tables in an SQL file with each customer but for some reason when I select a customer name from the combobox, nothing happens on the TableView, it just remains empty. There are no errors or any issues with the code, I just think that the way it is setup is whats causing the problem. Please review my code and advise me on how I can set these methods up in a better way to have the ComboBox trigger an SQL statement to populate the TableView
//MainController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package supremeinkcalcmk2;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javax.swing.DefaultComboBoxModel;
/**
* FXML Controller class
*
*/
public class MainController implements Initializable {
#FXML
public ComboBox<String> ComboBoxSelectCustomer;
#FXML
private TableView CustomerTableView;
#FXML
private TableColumn<BaseColor, String> BaseColor;
#FXML
private TableColumn<BaseColor, String> Price;
Connection connection;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
//Customer combo box
ComboBoxSelectCustomer.setOnAction(e -> System.out.println(ComboBoxSelectCustomer.getValue()));
buildDataComboBox();
buildDataTableView();
}
public void buildDataTableView() {
//viewtable db connect
ObservableList<BaseColor> dataCustomerViewTable = FXCollections.observableArrayList();
BaseColor.setCellValueFactory(new PropertyValueFactory<BaseColor, String>("BaseColor"));
Price.setCellValueFactory(new PropertyValueFactory<BaseColor, String>("Price"));
connection = SqlConnection.CustomerConnection();
try {
//problem
String SQL = "Select BaseColor, Price FROM " + ComboBoxSelectCustomer.getValue();
connection = SqlConnection.CustomerConnection();
ResultSet rs = connection.createStatement().executeQuery(SQL);
while (rs.next()) {
BaseColor BS = new BaseColor();
BS.BaseColor.set(rs.getString("BaseColor"));
BS.Price.set(rs.getString("Price"));
dataCustomerViewTable.add(BS);
}
CustomerTableView.setItems(dataCustomerViewTable);
} catch (Exception e) {
}
}
//combobox sql connection and fill data
public void buildDataComboBox() {
ObservableList<String> dataComboBox = FXCollections.observableArrayList();
connection = SqlConnection.CustomerConnection();
try {
String SQL = "Select Name From CustomerList";
ResultSet rs = connection.createStatement().executeQuery(SQL);
while (rs.next()) {
dataComboBox.add(rs.getString("Name"));
}
ComboBoxSelectCustomer.setItems(dataComboBox);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error Building ComboBox Data");
}
if (connection == null) {
System.exit(1);
System.out.println("Connection failed");
}
}
public boolean isDbConnected() {
try {
return connection.isClosed();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
Created a setOnAction event on ComboBoxSelectionCustomer which allowed the TableView to populate whenever the user changes options on the ComboBox.
ComboBoxSelectCustomer.setOnAction((event) -> {
});
I'm trying to read data from a database and set it as text in a textfield when I click a button. I can't for the life of me figure out why this code doesn't work. Any help is appreciated. Label works, and textfield doesn't. They're in the same anchor pane.
Here's the code from my FXMLcontroller.java file. I used SceneBuilder to create the UI.
package winfin_test;
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 javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
/**
*
* #author Sam
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
private TextField textField1 = new TextField();
#FXML
private void handleButtonData(ActionEvent event) {
try {
//Connect to the database
String host = "jdbc:mysql://localhost:3306/my_database";
String uName = "root";
String uPass = "data";
Connection con = DriverManager.getConnection(host, uName, uPass);
//Execute some SQL and load the records into the resultset
Statement stmt = con.createStatement();
String SQL = "Select * FROM data_test";
ResultSet rs = stmt.executeQuery(SQL);
//Move the cursor to the first record and get data
rs.next();
int id_col = rs.getInt("Auto_ID");
String id = Integer.toString(id_col);
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
String dob = rs.getString("Birthday");
String phone = rs.getString("Phone");
//Display the first record in the text fields
label.setText(first);
textField1.setText(last);
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
System.out.println("You clicked me!");
//label.setText("Well Done!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
}
The problem is that you never add the textField to your scene, you have the #FXML label for your Label, but then the textField you are trying to create dynamically, but never displaying. Instead, define the textfield in your .fxml document, and then edit your code to the following:
package winfin_test;
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 javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
/**
*
* #author Sam
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private TextField textField1;
#FXML
private void handleButtonData(ActionEvent event) {
try {
//Connect to the database
String host = "jdbc:mysql://localhost:3306/my_database";
String uName = "root";
String uPass = "data";
Connection con = DriverManager.getConnection(host, uName, uPass);
//Execute some SQL and load the records into the resultset
Statement stmt = con.createStatement();
String SQL = "Select * FROM data_test";
ResultSet rs = stmt.executeQuery(SQL);
//Move the cursor to the first record and get data
rs.next();
int id_col = rs.getInt("Auto_ID");
String id = Integer.toString(id_col);
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
String dob = rs.getString("Birthday");
String phone = rs.getString("Phone");
//Display the first record in the text fields
label.setText(first);
textField1.setText(last);
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
System.out.println("You clicked me!");
//label.setText("Well Done!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
}
I know it seems silly that you need to write #FXML before every single variable declaration that you are linking to an fx:id, but that's just the way it is. If you have multiple variables of the same type, (eg: a group of Labels) you only need to put it once and separate then with commas, like so:
#FXML
Label label1, label2, label3, label4;
Which saves you a bit of code.