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) -> {
});
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 created a book management application via javafx. Through this app we can perform add, search and delete operations. For the search i am using Table view to get all the details of the book searched by the user. So in the end i am getting the result displayed in the console but not in the table view
package Managemnet;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import connection.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
public class Searching {
Connection connect;
#FXML
TableView<Book> search_view ;
#FXML
ObservableList<Book> observeList;
#FXML
TableColumn<Book, Integer> Book_I;
#FXML
TableColumn<Book, String> Book_n;
#FXML
TableColumn<Book, String> publish;
#FXML
TableColumn<Book, Integer> ye;
#FXML
TextField sea_Book_name;
#FXML
TextField sea_pub;
#FXML
TextField sea_year;
#FXML
AnchorPane SearchPane;
#FXML
Button search;
public void search() throws ClassNotFoundException, SQLException{
Sql_query sql = new Sql_query();
sql.connect_sql();
connect = sql.getConnect();
observeList = FXCollections.<Book>observableArrayList();
search_view = new TableView<Book>();
Book_I=new TableColumn<Book ,Integer>();
Book_I.setCellValueFactory(new PropertyValueFactory<Book ,Integer>
("Book_id"));
Book_n=new TableColumn<Book ,String>();
Book_n.setCellValueFactory(new PropertyValueFactory<Book ,String>
("Book_name"));
publish=new TableColumn<Book ,String>();
publish.setCellValueFactory(new PropertyValueFactory<Book ,String>
("Publisher"));
ye=new TableColumn<Book ,Integer>();
ye.setCellValueFactory(new PropertyValueFactory<Book ,Integer>("year"));
String s1= sea_Book_name.getText();
String s2= sea_pub.getText();
String s= sea_year.getText();
int s3;
if(!s.isEmpty()){
s3=Integer.parseInt(s);
}
else s3=0;
ResultSet res;
Answer_from_dataset obj= new Answer_from_dataset();
res=obj.getAnswer(s1, s2, s3);
while(res.next()){
observeList.add(new Book(res.getInt(1), res.getString(2),
res.getString(3), res.getInt(4)));
//System.out.println(observeList);
}
search_view.setItems(observeList);
System.out.println(search_view);
}
package Managemnet;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Book {
SimpleStringProperty Book_name;
SimpleStringProperty Publisher;
SimpleIntegerProperty Book_id;
SimpleIntegerProperty year;
public Book(int book_id, String book_name, String publisher, int year) {
this.Book_name =new SimpleStringProperty(book_name);
this.Publisher =new SimpleStringProperty(publisher);
this.Book_id =new SimpleIntegerProperty (book_id);
this.year = new SimpleIntegerProperty(year);
}
public String getBook_name() {
return Book_name.get();
}
public String getPublisher() {
return Publisher.get();
}
public Integer getBook_id() {
return Book_id.get();
}
public Integer getYear() {
return year.get();
}
public void setBook_name(String book_name) {
Book_name.set(book_name);
}
public void setPublisher(String publisher) {
Publisher.set(publisher);;
}
public void setBook_id(int book_id) {
Book_id.set(book_id);;
}
public void setYear(int year) {
this.year.set(year);;
}
#Override
public String toString() {
return getBook_id() + " " + getBook_name() + " " + getPublisher() + " "
+ getYear();
}
}
So I ran into this issue with FXML when I did my first project with JavaFX.
I tried a lot of solutions with FXML but it took time and nothing worked. So I shifted over to using POJO's. This may not be ideally what you're looking for but it would give you a pretty good amount of flexibility with creating your table.
Ideally for the table itself you want to create a TableView
TableView<Book> table = new TableView();
Then for each column you want to create a TableColumn.. Now here you need to be careful
TableColumn<Book, String> col1 = new TableColumn<>("Name");
col.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getName()));
The values within the angle brackets is <Object Type, Data Type>
And then of course you can set your preferred width and what not. But the same process of creating TableColumns Repeats itself for the table you have. I get this might be a little more of lengthier process but its relatively easy to understand and most importantly it work.
Try this and let me know if it works! Cheers!!
I am fairly new to javafx and have been following a tutorial (http://code.makery.ch/library/javafx-8-tutorial/) where all my code has come from.
I am having an issue with populating a table with an xml file which I believe is because I want to switch scene first and then display the table on this new scene. In the guide they do it on just the first scene that loads, which if I do I can get to work fine, but when I want the table data to be viewable on a different scene, it doesn't seem to work. All I did was change where some of the code was located within the class to try to reflect this as I didn't want it on my first scene but now it won't display.
LibraryApp
package libraryapp;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import libraryapp.model.Book;
import libraryapp.model.BookListWrapper;
import libraryapp.view.HomeOverviewController;
import libraryapp.view.RootLayoutController;
public class LibraryApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
/**
* The data as an observable list of Books.
*/
private ObservableList<Book> bookData = FXCollections.observableArrayList();
/**
* Constructor
*/
public LibraryApp() {
// Add some sample data
bookData.add(new Book("Hans", "Muster"));
bookData.add(new Book("Ruth", "Mueller"));
bookData.add(new Book("Heinz", "Kurz"));
bookData.add(new Book("Cornelia", "Meier"));
bookData.add(new Book("Werner", "Meyer"));
bookData.add(new Book("Lydia", "Kunz"));
bookData.add(new Book("Anna", "Best"));
bookData.add(new Book("Stefan", "Meier"));
bookData.add(new Book("Martin", "Mueller"));
}
/**
* Returns the data as an observable list of Books.
* #return
*/
public ObservableList<Book> getBookData() {
return bookData;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("LibraryApp");
initRootLayout();
showHomeOverview();
}
/**
* Initializes the root layout and tries to load the last opened
* person file.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// Give the controller access to the main app.
RootLayoutController controller = loader.getController();
controller.setLibraryApp(this);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
// Try to load last opened person file.
File file = getBookFilePath();
if (file != null) {
loadBookDataFromFile(file);
}
}
/**
* Shows the book overview inside the root layout.
*/
public void showHomeOverview() {
try {
// Load home overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/HomeOverview.fxml"));
AnchorPane homeOverview = (AnchorPane) loader.load();
// Set home overview into the center of root layout.
rootLayout.setCenter(homeOverview);
// Give the controller access to the main app.
HomeOverviewController controller = loader.getController();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the main stage.
* #return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
/**
* Returns the book file preference, i.e. the file that was last opened.
* The preference is read from the OS specific registry. If no such
* preference can be found, null is returned.
*
* #return
*/
public File getBookFilePath() {
Preferences prefs = Preferences.userNodeForPackage(LibraryApp.class);
String filePath = prefs.get("filePath", null);
if (filePath != null) {
return new File(filePath);
} else {
return null;
}
}
/**
* Sets the file path of the currently loaded file. The path is persisted in
* the OS specific registry.
*
* #param file the file or null to remove the path
*/
public void setBookFilePath(File file) {
Preferences prefs = Preferences.userNodeForPackage(LibraryApp.class);
if (file != null) {
prefs.put("filePath", file.getPath());
// Update the stage title.
primaryStage.setTitle("LibraryApp - " + file.getName());
} else {
prefs.remove("filePath");
// Update the stage title.
primaryStage.setTitle("LibraryApp");
}
}
/**
* Loads book data from the specified file. The current book data will
* be replaced.
*
* #param file
*/
public void loadBookDataFromFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(BookListWrapper.class);
Unmarshaller um = context.createUnmarshaller();
// Reading XML from the file and unmarshalling.
BookListWrapper wrapper = (BookListWrapper) um.unmarshal(file);
bookData.clear();
bookData.addAll(wrapper.getBooks());
// Save the file path to the registry.
setBookFilePath(file);
} catch (Exception e) { // catches ANY exception
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not load data");
alert.setContentText("Could not load data from file:\n" + file.getPath());
alert.showAndWait();
}
}
/**
* Saves the current book data to the specified file.
*
* #param file
*/
public void saveBookDataToFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(BookListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping our book data.
BookListWrapper wrapper = new BookListWrapper();
wrapper.setBooks(bookData);
// Marshalling and saving XML to the file.
m.marshal(wrapper, file);
// Save the file path to the registry.
setBookFilePath(file);
} catch (Exception e) { // catches ANY exception
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
}
HomeOverViewController
package libraryapp.view;
import java.io.IOException;
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.layout.AnchorPane;
import libraryapp.view.BrowseController;
public class HomeOverviewController implements Initializable {
#FXML
private AnchorPane homePane;
#FXML
private void goToBrowse(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("Browse.fxml"));
homePane.getChildren().setAll(pane);
}
#FXML
private void goToManageAccount(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("ManageAccount.fxml"));
homePane.getChildren().setAll(pane);
}
#FXML
public void logout(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("Login.fxml"));
homePane.getChildren().setAll(pane);
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
BrowseController
package libraryapp.view;
import java.io.File;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import libraryapp.LibraryApp;
import libraryapp.model.Book;
public class BrowseController {
#FXML
private TableView<Book> bookTable;
#FXML
private TableColumn<Book, String> titleColumn;
#FXML
private Label titleLabel;
#FXML
private Label authorLabel;
#FXML
private Label isbnLabel;
#FXML
private Label quantityLabel;
#FXML
private AnchorPane browsePane;
// Reference to the main application.
private LibraryApp libraryApp;
/**
* The constructor.
* The constructor is called before the initialize() method.
*/
public BrowseController() {
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
#FXML
private void initialize() {
// Initialize the book table
titleColumn.setCellValueFactory(
cellData -> cellData.getValue().titleProperty());
// Clear person details.
showBookDetails(null);
// Listen for selection changes and show the person details when changed.
bookTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> showBookDetails(newValue));
}
/**
* Is called by the main application to give a reference back to itself.
*
* #param libraryApp
*/
public void setLibraryApp(LibraryApp libraryApp) {
this.libraryApp = libraryApp;
// Add observable list data to the table
bookTable.setItems(libraryApp.getBookData());
}
private void showBookDetails(Book book) {
if (book != null) {
// Fill the labels with info from the book object.
titleLabel.setText(book.getTitle());
authorLabel.setText(book.getAuthor());
isbnLabel.setText(book.getIsbn());
quantityLabel.setText(Integer.toString(book.getQuantity()));
} else {
// Book is null, remove all the text.
titleLabel.setText("");
authorLabel.setText("");
isbnLabel.setText("");
quantityLabel.setText("");
}
}
/**
* Called when the user clicks on the borrow button.
*/
#FXML
private void handleDeleteBook() {
int selectedIndex = bookTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
bookTable.getItems().remove(selectedIndex);
} else {
// Nothing selected.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(libraryApp.getPrimaryStage());
alert.setTitle("No Selection");
alert.setHeaderText("No book Selected");
alert.setContentText("Please select a book.");
alert.showAndWait();
}
}
#FXML
public void logout(ActionEvent event) throws IOException {
File bookFile = libraryApp.getBookFilePath();
libraryApp.saveBookDataToFile(bookFile);
AnchorPane pane = FXMLLoader.load(getClass().getResource("Login.fxml"));
browsePane.getChildren().setAll(pane);
}
}
The idea is that I want to press a button which calls goToBrowse which will load the Browse scene and then populate the table there with the data from the xml file. It goes to browse scene fine but does not populate the table.
Please excuse any messy code and any bad naming conventions as I am pretty new to this javafx stuff and have been trying to follow the tutorial that was mentioned before and tweak it to what I thought would be correct.
I believe it is the setLibraryApp that I want to be calling in the BrowseController, but what I have tried doesn't seem to work.
I want to move to next stage after Timer but when I run the page is frozen.
I want some help please to resolve this problem, I'm new in JavaFX .
I want to go to next screen after a specific time that I choose because this screen is a load screen
this is my code:
/*
* 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 chapitreapp;
import ressources.FadeInLeftTransition;
import ressources.FadeInRightTransition;
import ressources.FadeInTransition;
import ressources.config;
import ressources.config2;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.springframework.beans.*;
import org.springframework.context.*;
/**
* FXML Controller class
*
* #author anas
*/
public class LoadController implements Initializable {
#FXML
private Text lblWelcome;
#FXML
private Text lblRudy;
#FXML
private VBox vboxBottom;
#FXML
private Label lblClose;
Stage stage;
#FXML
private ImageView imgLoading;
/**
* Initializes the controller class.
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
longStart();
lblClose.setOnMouseClicked((MouseEvent event) -> {
Platform.exit();
System.exit(0);
});
// TODO
}
private void longStart() {
Service<ApplicationContext> service = new Service<ApplicationContext>() {
#Override
protected Task<ApplicationContext> createTask() {
return new Task<ApplicationContext>() {
#Override
protected ApplicationContext call() throws Exception {
ApplicationContext appContex = config.getInstance().getApplicationContext();
int max = appContex.getBeanDefinitionCount();
updateProgress(0, max);
for (int k = 0; k < max; k++) {
try
{
Thread.sleep(50);
updateProgress(k+1, max);
}
catch(InterruptedException e)
{
System.exit(0);
}
}
return appContex;
}
};
}
};
service.start();
service.setOnRunning((WorkerStateEvent event) -> {
new FadeInLeftTransition(lblWelcome).play();
new FadeInRightTransition(lblRudy).play();
new FadeInTransition(vboxBottom).play();
});
service.setOnSucceeded((WorkerStateEvent event) -> {
config2 config = new config2();
config.newStage(stage, lblClose, "/chapitreapp/FXMLDocument.fxml", "Sample Apps", true, StageStyle.UNDECORATED, false);
});
}
}
where did I go wrong?
Something along these lines, in your onSucceeded event handler, or a method that it calls...
try {
URL url = this.getClass().getResource("nextScene.fxml");
if (url != null) {
FXMLLoader loader = new FXMLLoader(url);
Parent root = loader.load(url);
Scene newScene = new Scene(root);
this.getStage().setScene(newScene);
} else {
System.out.println("URL was null");
}
} catch (Exception e) {
System.out.println(e);
}
In your controller, you will need to have some means of setting the stage, either via a constructor that accepts the Stage object or via a setStage() method. I've used a getStage() method above to access the Stage and set the new Scene object on it.
You could also use the static FXMLLoader load method: Parent root = FXMLLoader.load(url);
This may also be of benefit: https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx1
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.