How to use onKeyPressed in JavaFX scene builder? - javafx

I'm new to JavaFX scene builder, and I developed text editor by using it, but at last, I got a problem, where I want to call a function when I pressed a combination of keys e.g, suppose I press CTRL+S, then it must call a function from my controller.java.
[Here is my javaScene builder pic][1]
Main.java
package sample;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
Scene scene = new Scene(root, 300, 275);
primaryStage.setScene(scene);
scene.getStylesheets().add("style.css");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
**
Controller.java
package sample;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.sql.SQLOutput;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyEvent;
import javafx.stage.FileChooser;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import javax.xml.soap.Text;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.scene.input.KeyCode;
public class Controller implements EventHandler <KeyEvent> {
boolean doesFileHasName=false;
File selectedFile1;
File selectedFile;
FileChooser fileChooser = new FileChooser();
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private TextArea TextArea;
#FXML
private MenuBar MenuBar;
#FXML
private MenuItem createFile;
#FXML
private Text fileName;
#FXML
private javafx.scene.text.Text text;
#Override
public void handle(KeyEvent keyEvent)
{
}
#FXML
public void onKeyPressed(KeyEvent keyEvent) {
if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.C) {
System.out.println("Control Down: " + keyEvent.isControlDown() + " " + keyEvent.getCode() + " was pressed!");
}
if (keyEvent.isAltDown() && keyEvent.getCode() == KeyCode.C) {
System.out.println("Alt Down: " + keyEvent.isAltDown() + " " + keyEvent.getCode() + " was pressed!");
}
}
#FXML
void editSaveAs()
{
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Java files (*.java)", "*.java");
/* new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");*/
fileChooser.getExtensionFilters().add(extFilter);
selectedFile = fileChooser.showSaveDialog(null);
if(selectedFile != null){
SaveFile(TextArea.getText(), selectedFile);
text.setText(selectedFile.getName());
doesFileHasName=true;
}
}
#FXML
void editNew()
{
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("new.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.setTitle("Untitled");
stage.setScene(new Scene(root1));
stage.show();
}catch (Exception e){
System.out.println("Can't open a new window");
}
}
String[] storeButton = new String[2];
#FXML
void editOpen()
{
selectedFile1 = fileChooser.showOpenDialog(null);
if (selectedFile1!=null)
{
text.setText(selectedFile1.getName());
doesFileHasName = true;
try{
FileReader fileReader = new FileReader(selectedFile1);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String s ;
String f="" ;
while((s=bufferedReader.readLine())!=null)
{
f=f+s+"\n";
}
TextArea.setText(f);
bufferedReader.close();
}catch(Exception error)
{
System.out.println("hello world!!!");
}
}
}
#FXML
void Save() {
if (doesFileHasName == false) {
editSaveAs();
//System.out.println(selectedFile.getName());
} else {
if (doesFileHasName == true) {
try {
if(selectedFile!= null && text.getText().equals( selectedFile.getName())) {
SaveFile(TextArea.getText(), selectedFile);
System.out.println("selectFile block is done");
}else
{
if(selectedFile1!=null && text.getText().equals(selectedFile1.getName())) {
SaveFile(TextArea.getText(), selectedFile1);
System.out.println("selectFile1 block is done");
}
}
}catch (Exception E) {
System.out.println(E);
}
}}
}
private void SaveFile(String content, File file){
try {
FileWriter fileWriter;
fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Main.class
.getName()).log(Level.SEVERE, null, ex);
}
}
#FXML
void onKeyTyped()
{
TextArea.setStyle("-fx-font-size: 18");
if (doesFileHasName == true) {
try {
if(selectedFile!= null && text.getText().equals( selectedFile.getName())) {
SaveFile(TextArea.getText(), selectedFile);
//System.out.println("selectFile block is done");
}else
{
if(selectedFile1!=null && text.getText().equals(selectedFile1.getName())) {
SaveFile(TextArea.getText(), selectedFile1);
//System.out.println("selectFile1 block is done");
}
}
}catch (Exception E) {
System.out.println(E);
}
}
}
#FXML
void initialize() {
text.setText("Untitled");
assert TextArea != null : "fx:id=\"TextArea\" was not injected: check your FXML file 'textEditor.fxml'.";
assert MenuBar != null : "fx:id=\"MenuBar\" was not injected: check your FXML file 'textEditor.fxml'.";
}
}
**
sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.ScrollBar?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>
<AnchorPane id="AnchorPane" onKeyPressed="#onKeyPressed" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="499.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<MenuBar fx:id="MenuBar" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" onAction="#editNew" text="New " />
<MenuItem mnemonicParsing="false" onAction="#editOpen" text="Open " />
<MenuItem mnemonicParsing="false" onAction="#Save" text="Save " />
<MenuItem mnemonicParsing="false" onAction="#editSaveAs" text="Save As... " />
<MenuItem mnemonicParsing="false" text="Exit" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Undo (Ctrl+Z)" />
<MenuItem mnemonicParsing="false" text="Cut (Ctrl+X)" />
<MenuItem mnemonicParsing="false" text="Copy (Ctrl+C)" />
<MenuItem mnemonicParsing="false" text="Paste (Ctrl+V)" />
<MenuItem mnemonicParsing="false" text="Delete (Del)" />
<MenuItem mnemonicParsing="false" text="Find... (Ctrl+F)" />
<MenuItem mnemonicParsing="false" text="Replace... (Ctrl+H)" />
<MenuItem mnemonicParsing="false" text="Select All (Ctrl+A)" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Font Size">
<items>
<MenuItem mnemonicParsing="false" text="Unspecified Action">
<graphic>
<ScrollBar orientation="VERTICAL" />
</graphic>
</MenuItem>
</items>
</Menu>
</menus>
</MenuBar>
<TextArea fx:id="TextArea" layoutY="25.0" onKeyTyped="#onKeyTyped" prefHeight="474.0" prefWidth="500.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="51.0" />
<Text fx:id="text" layoutX="7.0" layoutY="48.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Text" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
<font>
<Font size="15.0" />
</font></Text>
</children>
</AnchorPane>
help will be appreciated...

Related

Javafx How to display image captured from web cam in imageview in another scene

I have this fxml layout. When I click on take photo it opens a screen for me to take a picture using web cam
Dialog layout to take pic from web cam
I want the picture captured on the web cam to replace the dummy image on the fxml layout beside take photo button.Here are my files:
FXML layout containing dummy image and take photo button
<HBox prefHeight="79.0" prefWidth="232.0" spacing="30.0">
<children>
<VBox prefHeight="100.0" prefWidth="100.0">
<children>
<ImageView fx:id="profilePic" fitHeight="99.0" fitWidth="118.0" nodeOrientation="INHERIT" pickOnBounds="true">
<image>
<Image url="#../images/profile_photo.png" />
</image>
</ImageView>
</children>
</VBox>
<VBox prefHeight="200.0" prefWidth="100.0">
<children>
<Button mnemonicParsing="false" onAction="#takePhoto" text="Take Photo">
<font>
<Font size="13.0" />
</font>
<VBox.margin>
<Insets bottom="20.0" top="10.0" />
</VBox.margin>
</Button>
<Button mnemonicParsing="false" onAction="#pickPhoto" prefHeight="31.0" prefWidth="85.0" text="Upload
">
<font>
<Font size="13.0" />
</font>
<VBox.margin>
<Insets bottom="10.0" />
</VBox.margin></Button>
</children>
</VBox>
</children>
</HBox>
Controller for the FXML Layout
public class AddParentController implements Initializable {
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void doAll(){
ImageSelection.getImageSelectionInstance().imageProperty()
.addListener((obs, oldImage, newImage) -> profilePic.setImage(newImage));
}
public void takePhoto(){
try {
Stage dialogStage = new Stage(StageStyle.UNDECORATED);
BorderPane root = FXMLLoader.load(getClass().getResource("../views/WebCamPreview.fxml"));
Scene scene = new Scene(root, 850, 390);
dialogStage.setUserData("fromAddParent");
dialogStage.initModality(Modality.APPLICATION_MODAL);
dialogStage.setScene(scene);
dialogStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Dialog Layout containing WebCam Preview
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.FlowPane?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<BorderPane prefHeight="390.0" prefWidth="850.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controllers.WebCamPreviewController">
<!-- TODO Add Nodes -->
<bottom>
<FlowPane fx:id="fpBottomPane" alignment="CENTER" columnHalignment="CENTER" hgap="50.0" prefHeight="80.0" prefWidth="200.0" style="-fx-background-color:#ccc;">
<children>
<Button fx:id="btnStartCamera" focusTraversable="false" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#stopCamera" prefHeight="40.0" prefWidth="120.0" text="Capture">
<font>
<Font name="Segoe UI" size="18.0" fx:id="x1" />
</font>
</Button>
<Button fx:id="btnProceedCamera" focusTraversable="false" font="$x1" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#proceed" prefHeight="40.0" prefWidth="120.0" text="Proceed" />
<Button fx:id="btnResetCamera" focusTraversable="false" font="$x1" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#startCamera" prefHeight="40.0" prefWidth="120.0" text="Reset" />
<Button fx:id="btnDisposeCamera" focusTraversable="false" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#disposeCamera" prefHeight="40.0" prefWidth="120.0" text="Close">
<font>
<Font name="Segoe UI" size="18.0" fx:id="x11" />
</font>
</Button>
</children>
</FlowPane>
</bottom>
<center>
<BorderPane fx:id="bpWebCamPaneHolder" prefHeight="200.0" prefWidth="200.0">
<center>
<ImageView fx:id="imgWebCamCapturedImage" fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" BorderPane.alignment="CENTER" />
</center></BorderPane>
</center>
<top>
<GridPane minHeight="-Infinity" minWidth="-Infinity" prefHeight="80.0" style="-fx-background-color:#ccc;
">
<children>
<Label text="Webcam Image Capture" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.halignment="CENTER" GridPane.hgrow="ALWAYS" GridPane.rowIndex="0" GridPane.rowSpan="1" GridPane.valignment="CENTER" GridPane.vgrow="ALWAYS">
<font>
<Font name="Segoe UI" size="34.0" />
</font>
<GridPane.margin>
<Insets top="10.0" />
</GridPane.margin>
</Label>
</children>
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" maxWidth="795.0" minWidth="10.0" prefWidth="418.0" />
<ColumnConstraints hgrow="SOMETIMES" maxWidth="502.0" minWidth="10.0" prefWidth="482.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
</GridPane>
</top>
</BorderPane>
WebCam Preview Controller
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.ResourceBundle;
import com.github.sarxos.webcam.WebcamPanel;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import com.github.sarxos.webcam.Webcam;
import javafx.stage.Stage;
public class WebCamPreviewController implements Initializable {
#FXML Button btnStartCamera;
#FXML Button btnProceedCamera;
#FXML Button btnDisposeCamera,btnResetCamera;
#FXML BorderPane bpWebCamPaneHolder;
#FXML FlowPane fpBottomPane;
#FXML ImageView imgWebCamCapturedImage;
private BufferedImage grabbedImage;
private WebcamPanel selWebCamPanel = null;
private Webcam selWebCam = null;
private boolean stopCamera = false;
private ObjectProperty<Image> imageProperty = new SimpleObjectProperty<Image>();
Image mainiamge;
private String userData;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
fpBottomPane.setDisable(true);
try{
initializeWebCam(0);
}catch(Exception e){
e.printStackTrace();
}
Platform.runLater(() -> {
userData = (String) fpBottomPane.getScene().getWindow().getUserData();
setImageViewSize();
});
}
protected void setImageViewSize() {
double height = bpWebCamPaneHolder.getHeight();
double width = bpWebCamPaneHolder.getWidth();
imgWebCamCapturedImage.setFitHeight(height);
imgWebCamCapturedImage.setFitWidth(width);
imgWebCamCapturedImage.prefHeight(height);
imgWebCamCapturedImage.prefWidth(width);
imgWebCamCapturedImage.setPreserveRatio(true);
}
protected void initializeWebCam(final int webCamIndex) {
Task<Void> webCamIntilizer = new Task<Void>() {
#Override
protected Void call() throws Exception {
if(selWebCam == null)
{
selWebCam = Webcam.getWebcams().get(webCamIndex);
selWebCam.open();
}else
{
closeCamera();
selWebCam = Webcam.getWebcams().get(webCamIndex);
selWebCam.open();
}
startWebCamStream();
return null;
}
};
new Thread(webCamIntilizer).start();
fpBottomPane.setDisable(false);
btnProceedCamera.setDisable(true);
btnResetCamera.setDisable(true);
}
protected void startWebCamStream() {
stopCamera = false;
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
while (!stopCamera) {
try {
if ((grabbedImage = selWebCam.getImage()) != null) {
Platform.runLater(new Runnable() {
#Override
public void run() {
mainiamge = SwingFXUtils
.toFXImage(grabbedImage, null);
imageProperty.set(mainiamge);
}
});
grabbedImage.flush();
}
} catch (Exception e) {
} finally {
}
}
return null;
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
imgWebCamCapturedImage.imageProperty().bind(imageProperty);
}
private void closeStage() {
((Stage) fpBottomPane.getScene().getWindow()).close();
}
private void closeCamera()
{
if(selWebCam != null)
{
selWebCam.close();
}
}
public void proceed(){
ImageSelection.getImageSelectionInstance().setImage(imgWebCamCapturedImage.getImage());
AddParentController apc = new AddParentController();
apc.doAll();
closeStage();
}
public void proceedToAddPartner(){
}
public void stopCamera(ActionEvent event)
{
stopCamera = true;
btnStartCamera.setDisable(true);
btnResetCamera.setDisable(false);
btnProceedCamera.setDisable(false);
}
public void startCamera(ActionEvent event)
{
stopCamera = false;
startWebCamStream();
btnStartCamera.setDisable(false);
btnResetCamera.setDisable(true);
btnProceedCamera.setDisable(true);
}
public void disposeCamera(ActionEvent event)
{
//stopCamera = true;
//closeCamera();
//Webcam.shutdown();
//btnStopCamera.setDisable(true);
//btnStartCamera.setDisable(true);
closeStage();
}
}
Image Model
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.image.Image;
public class ImageSelection {
private final ObjectProperty<Image> image = new SimpleObjectProperty<>();
private static ImageSelection imageSelectionInstance= new ImageSelection();
private ImageSelection(){}
public static ImageSelection getImageSelectionInstance() {
return imageSelectionInstance;
}
public ObjectProperty<Image> imageProperty() {
return image ;
}
public final void setImage(Image image) {
imageProperty().set(image);
}
public final Image getImage()
{
return imageProperty().get();
}
}
The challenge is to make the Image captured by the web cam to display in profilPic ImageView on the AddParent FXML Layout.

JavaFX FXML Show Updated TableView

I'm having issues showing new additions to a class in a TableView for my JavaFX/FXML program. I've looked at countless tutorials but the missing piece still escapes me.
I had some errors that got fixed here: JavaFX Adding Rows to TableView on Different Page
And then found a new tutorial to sort of follow that explained things a bit better than the first one I was following (their app is a bit different than what I have to do) here: http://code.makery.ch/library/javafx-8-tutorial/part2/
I have an output printing the name field out to the console just to make sure it is pulling the right values from the add form. I also changed the way I navigated between Add Part and the Main window (nothing else works right now). I feel so silly asking this, but Java is the one language I haven't been able to wrap my head around.
Any ideas on why it isn't updating are greatly appreciated.
IMS.java
package ims;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
*
* #author chelseacamper
*/
public class IMS extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Part> partData = FXCollections.observableArrayList();
public IMS() {
partData.add(new Part("Part A", 3, 4.00, 1, 5));
partData.add(new Part("Part B", 2, 14.00, 1, 15));
}
public ObservableList<Part> getPartData(){
return partData;
}
#Override
public void start(Stage stage) throws Exception {
// Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = (Parent) loader.load();
FXMLDocumentController ctrl = loader.getController();
ctrl.setMainApp(this);
Scene scene = new Scene(root);
scene.getStylesheets().add("style.css");
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLDocumentController.java
package ims;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
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.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
/**
*
* #author chelseacamper
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private TableView<Part> partTable;
#FXML
private TableColumn<Part, Integer> partIDColumn;
#FXML
private TableColumn<Part, String> nameColumn;
#FXML
private TableColumn<Part, Integer> inventoryColumn;
#FXML
private TableColumn<Part, Double> priceColumn;
private IMS mainApp;
public FXMLDocumentController(){
}
#FXML
private void addPart(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("addPart.fxml"));
Parent add_part_parent = (Parent) loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(add_part_parent));
stage.show();
}
#FXML
private void modifyPart(ActionEvent event) throws IOException {
Parent modify_part_parent = FXMLLoader.load(getClass().getResource("modifyPart.fxml"));
Scene modify_part_scene = new Scene(modify_part_parent);
modify_part_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(modify_part_scene);
app_stage.show();
}
#FXML
private void addProduct(ActionEvent event) throws IOException {
Parent add_product_parent = FXMLLoader.load(getClass().getResource("addProduct.fxml"));
Scene add_product_scene = new Scene(add_product_parent);
add_product_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(add_product_scene);
app_stage.show();
}
#FXML
private void modifyProduct(ActionEvent event) throws IOException {
Parent modify_product_parent = FXMLLoader.load(getClass().getResource("modifyProduct.fxml"));
Scene modify_product_scene = new Scene(modify_product_parent);
modify_product_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(modify_product_scene);
app_stage.show();
}
#FXML
private void closeProgram(ActionEvent event) throws IOException {
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.close();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
// inventoryColumn.setCellValueFactory(cellData -> cellData.getValue().instockProperty().asObject());
// priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty().asObject());
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
inventoryColumn.setCellValueFactory(new PropertyValueFactory<>("instock"));
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
}
public void setMainApp(IMS mainApp) {
this.mainApp = mainApp;
// Add observable list data to the table
partTable.setItems(mainApp.getPartData());
}
#FXML
private void handleDeletePart(){
int selectedIndex = partTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0){
partTable.getItems().remove(selectedIndex);
} else {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("No Part Selected");
alert.setHeaderText("No Part Selected");
alert.setContentText("Please select the part you would like to delete.");
alert.showAndWait();
}
}
}
FXMLDocument.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.collections.*?>
<?import fxmltableview.*?>
<?import ims.Part?>
<?import ims.Inhouse?>
<?import ims.Outsourced?>
<BorderPane id="main" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.FXMLDocumentController" >
<top>
<Label fx:id="mainTitle" text="Inventory Management System" />
</top>
<center>
<HBox fx:id="holding">
<children>
<VBox styleClass="contentBox">
<children>
<HBox styleClass="topBox">
<HBox styleClass="subHeading">
<Label text="Parts" />
</HBox>
<HBox styleClass="searchBox">
<Button text="Search" />
<TextField />
</HBox>
</HBox>
<TableView fx:id="partTable" styleClass="dataTable">
<columns>
<TableColumn fx:id="partIDColumn" text="Part ID" />
<TableColumn fx:id="nameColumn" text="Part Name" />
<TableColumn fx:id="inventoryColumn" text="Inventory Level" />
<TableColumn fx:id="priceColumn" text="Price/Cost per Unit" />
</columns>
</TableView>
<HBox styleClass="modificationButtons">
<children>
<Button onAction="#addPart" text="Add" />
<Button onAction="#modifyPart" text="Modify" />
<Button text="Delete" />
</children>
</HBox>
</children>
</VBox>
<VBox styleClass="contentBox">
<children>
<HBox styleClass="topBox">
<HBox styleClass="subHeading">
<Label text="Products" />
</HBox>
<HBox styleClass="searchBox">
<Button text="Search" />
<TextField />
</HBox>
</HBox>
<TableView fx:id="productTable" styleClass="dataTable">
<columns>
<TableColumn text="Part ID" />
<TableColumn text="Part Name" />
<TableColumn text="Inventory Level" />
<TableColumn text="Price/Cost per Unit" />
</columns>
</TableView>
<HBox styleClass="modificationButtons">
<children>
<Button onAction="#addProduct" text="Add" />
<Button onAction="#modifyProduct" text="Modify" />
<Button text="Delete" />
</children>
</HBox>
</children>
</VBox>
</children>
</HBox>
</center>
<bottom>
<HBox fx:id="exitButton">
<children>
<Button onAction="#closeProgram" text="Exit" />
</children>
</HBox>
</bottom>
</BorderPane>
Part.java
package ims;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* #author chelseacamper
*/
public class Part {
private final SimpleStringProperty name;
private final SimpleIntegerProperty instock;
private final SimpleDoubleProperty price;
private final SimpleIntegerProperty min;
private final SimpleIntegerProperty max;
public Part(){
this("", 0, 0.00, 0, 0);
}
public Part(String name, int instock, double price, int min, int max) {
this.name = new SimpleStringProperty(name);
this.instock = new SimpleIntegerProperty(instock);
this.price = new SimpleDoubleProperty(price);
this.min = new SimpleIntegerProperty(min);
this.max = new SimpleIntegerProperty(max);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
public Double getPrice() {
return price.get();
}
public void setPrice(Double price) {
this.price.set(price);
}
public DoubleProperty priceProperty(){
return price;
}
public int getInstock() {
return instock.get();
}
public void setInstock(int instock) {
this.instock.set(instock);
}
public IntegerProperty instockProperty(){
return instock;
}
public int getMin() {
return min.get();
}
public void setMin(int min) {
this.min.set(min);
}
public IntegerProperty minProperty(){
return min;
}
public int getMax() {
return max.get();
}
public void setMax(int max) {
this.max.set(max);
}
public IntegerProperty maxProperty(){
return max;
}
}
addPartController.java
package ims;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* #author chelseacamper
*/
public class AddPartController implements Initializable {
#FXML
ToggleButton inhouse;
#FXML
ToggleButton outsourced;
#FXML
Label inhouseLabel;
#FXML
Label outsourcedLabel;
#FXML
TextField inhouseTextField;
#FXML
TextField outsourcedTextField;
#FXML
private TableView<Part> partTable;
#FXML
private TextField partNameField;
#FXML
private TextField partInstockField;
#FXML
private TextField partPriceField;
#FXML
private TextField partMaxField;
#FXML
private TextField partMinField;
#FXML
private Button cancel;
#FXML
private Button save;
private Part part = new Part();
// private ObservableList<Part> partData = FXCollections.observableArrayList();
private ObservableList<Part> tableItems;
/**
* Initializes the controller class.
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
inhouseLabel.visibleProperty().bind( inhouse.selectedProperty() );
outsourcedLabel.visibleProperty().bind( outsourced.selectedProperty() );
inhouseTextField.visibleProperty().bind( inhouse.selectedProperty() );
outsourcedTextField.visibleProperty().bind( outsourced.selectedProperty() );
inhouseLabel.managedProperty().bind( inhouse.selectedProperty() );
outsourcedLabel.managedProperty().bind( outsourced.selectedProperty() );
inhouseTextField.managedProperty().bind( inhouse.selectedProperty() );
outsourcedTextField.managedProperty().bind( outsourced.selectedProperty() );
}
#FXML
public void addInhouse(ActionEvent event) throws IOException{
// Part tempPart = new Part(partNameField.getText(),
// Integer.parseInt(partInstockField.getText()),
// Double.parseDouble(partPriceField.getText()),
// Integer.parseInt(partMaxField.getText()),
// Integer.parseInt(partMinField.getText()));
// tableItems.add(new Part(partNameField.getText(),
// Integer.parseInt(partInstockField.getText()),
// Double.parseDouble(partPriceField.getText()),
// Integer.parseInt(partMaxField.getText()),
// Integer.parseInt(partMinField.getText())
// ));
part
.setName(partNameField.getText());
part.setPrice(Double.parseDouble(partPriceField.getText()));
part.setInstock(Integer.parseInt(partInstockField.getText()));
part.setMin(Integer.parseInt(partMinField.getText()));
part.setMax(Integer.parseInt(partMaxField.getText()));
System.out.println(partNameField.getText());
Stage stage = (Stage) cancel.getScene().getWindow();
stage.close();
}
#FXML
private void close(ActionEvent event) throws IOException {
Stage stage = (Stage) cancel.getScene().getWindow();
stage.close();
}
void setTableItems(ObservableList<Part> tableItems) {
this.tableItems = tableItems;
}
}
addPart.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane id="addPage" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.AddPartController">
<stylesheets>
<String fx:value="style.css" />
</stylesheets>
<fx:define>
<ToggleGroup fx:id="inOutGroup" />
</fx:define>
<center>
<VBox fx:id="verticalHolding">
<children>
<HBox fx:id="topRow">
<Label text="Add Part"/>
<RadioButton fx:id="inhouse" toggleGroup="$inOutGroup" text="In-House"/>
<RadioButton fx:id="outsourced" toggleGroup="$inOutGroup" selected="true" text="Outsourced"/>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="ID" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField promptText="Auto Gen - Disabled" disable="true" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Name" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partNameField" promptText="Part Name" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Inv" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partInstockField" promptText="Inv" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Price/Cost" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partPriceField" promptText="Price/Cost" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Max" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField styleClass="smallTextField" fx:id="partMaxField" promptText="Max" />
<Label text="Min" />
<TextField styleClass="smallTextField" fx:id="partMinField" promptText="Min" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label fx:id="inhouseLabel" text="Machine ID" />
<Label fx:id="outsourcedLabel" text="Company Name" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="inhouseTextField" promptText="Mach ID" />
<TextField fx:id="outsourcedTextField" promptText="Comp Nm" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
</HBox>
<HBox styleClass="halfWidthRight">
<Button onAction="#addInhouse" fx:id="save" text="Save" />
<Button onAction="#close" fx:id="cancel" text="Cancel" />
</HBox>
</HBox>
</children>
</VBox>
</center>
</BorderPane>

JavaFX popup not working

I’m trying to learn how to get a JavaFX popup window to open from a menu item click. I finally got a new window to open but I can’t seem to make it modal. Here's my code:
Scene 1 FXML:
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sceneswitchtest.Scene_1Controller">
<children>
<Button fx:id="button" layoutX="126" layoutY="90" onAction="#handleButtonAction" text="Click Me!" />
<Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
<MenuBar fx:id="menuBar" layoutX="40.0" layoutY="27.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
<MenuItem fx:id="MenuItemOpenScene2" mnemonicParsing="false" onAction="#OpenScene2" text="Open Scene 2" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
Popup FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sceneswitchtest.Scene_2Controller">
</AnchorPane>
Scene 1 controller:
package sceneswitchtest;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class Scene_1Controller {
#FXML
private Button button;
#FXML
private Label label;
#FXML
private MenuBar menuBar;
#FXML
private MenuItem MenuItemOpenScene2;
#FXML
void OpenScene2(ActionEvent event) throws IOException {
Stage appStage = (Stage) ((Node) menuBar).getScene().getWindow();
Parent settingsParent = FXMLLoader.load(this.getClass().getResource("Scene_2.fxml"));
Scene settingsScene = new Scene(settingsParent);
appStage.setScene(settingsScene);
// appStage.initModality(Modality.WINDOW_MODAL);
// appStage.initOwner(menuBar.getScene().getWindow());
appStage.show();
}
#FXML
void handleButtonAction(ActionEvent event) throws IOException {
}
}
Note: In the above code, the lines commented out failed as well as he use of Modality.APPLICATION_MODAL
Scene 2 (popup) controller:
package sceneswitchtest;
public class Scene_2Controller {
}
main method:
package sceneswitchtest;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author eric
*/
public class SceneSwitchTest extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Scene_1.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Here is the code changes I made in order to get the popup to work.
#FXML
void OpenScene2(ActionEvent event) throws IOException {
Parent settingsParent = FXMLLoader.load(this.getClass().getResource("/sceneswitchtest/Scene_2.fxml"));
Scene settingsScene = new Scene(settingsParent);
Stage popup = new Stage();
popup.setScene(settingsScene);
popup.initModality(Modality.WINDOW_MODAL);
popup.initOwner(menuBar.getScene().getWindow());
popup.show();
}
I would like to thank MBec for pointing me in the right direction.

Load Exception in fxml

I want my inventory_layout to load when i click on the first button but i am getting load exception there while the same code works fine with other fxmls.
Path of controller is right.
fxml is in the right place.
Here is my code- Inventory
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import pharmbooks.Utils.DbSingleton;
import pharmbooks.Utils.UIController;
import java.io.IOException;
public class MainController {
#FXML
private BorderPane borderPane;
#FXML
public void initInventory(ActionEvent actionEvent) throws IOException{
UIController<InventoryController> uiController=new UIController<InventoryController>();
uiController.setUp(borderPane,"inventory_layout.fxml");
}
public void initPurchase(ActionEvent actionEvent) throws IOException{
UIController<PurchaseController> uiController=new UIController<>();
uiController.setUp(borderPane,"purchase_layout.fxml");
}
}
Ui Controller
public class UIController<T> {
private T controller;
private Pane pane;
public T getController() {
return controller;
}
public void setUp(Pane mainPane,String fxmlLocation){
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getClassLoader().getResource(fxmlLocation));
pane = loader.load();
controller = loader.getController();
mainPane.getChildren().clear();
mainPane.getChildren().add(pane);
}catch (Exception e){
System.out.println(UIController.class.getSimpleName()+" "+e.toString());
}
} }
This code works well in ubuntu though :/
here is the error :
UIController javafx.fxml.LoadException:
/Users/manyamadan/Desktop/Everything/pharmbooks-v2/target/classes/inventory_layout.fxml
Inventory controller :
public class InventoryController implements Initializable{
public TableColumn batchId;
public TableColumn company;
public TableColumn name;
public TableColumn packing;
public TableColumn quantity;
public TableColumn expiry;
public TableColumn mrp;
#FXML
private TableView<Inventory> personTable;
public void InventoryController()
{
}
public void initialize(URL location, ResourceBundle resources) {
batchId.setCellValueFactory(new PropertyValueFactory<Inventory, String>("BATCH_ID"));
company.setCellValueFactory(new PropertyValueFactory<Inventory, String>("COMPANY"));
name.setCellValueFactory(new PropertyValueFactory<Inventory, String>("PRODUCT_NAME"));
packing.setCellValueFactory(new PropertyValueFactory<Inventory, String>("PACKING"));
quantity.setCellValueFactory(new PropertyValueFactory<Inventory, Integer>("QUANTITY"));
expiry.setCellValueFactory(new PropertyValueFactory<Inventory, String>("EXPIRY_DATE"));
mrp.setCellValueFactory(new PropertyValueFactory<Inventory, String>("MRP"));
personTable.setEditable(true);
personTable.setItems(InventoryData.getInstance().getList());
// name.setOnEditCommit(TableColumn.CellEditEvent(Inventory,String)event);
Inventory inventory_data = personTable.getSelectionModel().getSelectedItem();
System.out.println(inventory_data.getPRODUCT_NAME()+ "" + inventory_data.getBATCH_ID());
personTable.setOnKeyPressed(event -> {
TablePosition<Inventory, ?> pos = personTable.getFocusModel().getFocusedCell() ;
if (pos != null) {
AnchorPane anchorPane= null;
try {
anchorPane = FXMLLoader.load(getClass().getClassLoader().getResource("edit_inventory_data.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
Stage stage=new Stage();
stage.setTitle("Apna Dialog");
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(StageManager.getInstance().getPrimaryStage());
Scene scene = new Scene(anchorPane);
stage.setScene(scene);
stage.showAndWait();
}
});
name.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Inventory, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Inventory, String> t) {
System.out.println("ON edit commit" + t);
((Inventory) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setPRODUCT_NAME(t.getNewValue());
}
}
);
}
#FXML
public void addData(ActionEvent actionEvent) throws IOException {
AnchorPane anchorPane= FXMLLoader.load(getClass().getClassLoader().getResource("add_data_inventory.fxml"));
Stage stage=new Stage();
stage.setTitle("Apna Dialog");
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(StageManager.getInstance().getPrimaryStage());
Scene scene = new Scene(anchorPane);
stage.setScene(scene);
stage.showAndWait();
personTable.setItems(InventoryData.getInstance().getList());
}
}
inventory_layout.fxml
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<BorderPane maxHeight="600.0" maxWidth="800.0" prefHeight="600.0" prefWidth="800.0" stylesheets="#beautify_inventory.css" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pharmbooks.controllers.InventoryController">
<center>
<TableView fx:id="personTable" prefWidth="10000.0" BorderPane.alignment="CENTER">
<columns>
<TableColumn fx:id="batchId" prefWidth="75.0" text="BatchId" />
<TableColumn fx:id="packing" prefWidth="75.0" text="packing" />
<TableColumn fx:id="quantity" prefWidth="75.0" text="quantity" />
<TableColumn fx:id="expiry" prefWidth="75.0" text="expiry" />
<TableColumn fx:id="mrp" prefWidth="75.0" text="mrp" />
</columns>
</TableView>
</center>
<top>
<HBox prefHeight="67.0" prefWidth="800.0" BorderPane.alignment="CENTER">
<children>
<TextField prefHeight="47.0" prefWidth="163.00009155273438">
<HBox.margin>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</HBox.margin>
</TextField>
<Button mnemonicParsing="false" onAction="#addData" text="Button">
<HBox.margin>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
</HBox.margin>
</Button>
<Button mnemonicParsing="false" prefHeight="39.0" prefWidth="121.0" text="Button">
<HBox.margin>
<Insets bottom="20.0" right="20.0" top="20.0" />
</HBox.margin>
</Button>
<Button mnemonicParsing="false" prefHeight="39.0" prefWidth="129.0" text="Button">
<HBox.margin>
<Insets bottom="20.0" top="20.0" />
</HBox.margin>
</Button>
</children>
</HBox>
</top>
</BorderPane>
In inventory_layout.fxml you set fx:id attribute to all table columns:
<TableColumn fx:id="batchId" prefWidth="75.0" text="BatchId" />
<TableColumn fx:id="packing" prefWidth="75.0" text="packing" />
<TableColumn fx:id="quantity" prefWidth="75.0" text="quantity" />
<TableColumn fx:id="expiry" prefWidth="75.0" text="expiry" />
<TableColumn fx:id="mrp" prefWidth="75.0" text="mrp" />
but in InventoryController you does not annotate this components with #FXML. Witout this annotations FXMLLoader will not be able to inject correct objects to controller. Correct code:
#FXML
public TableColumn batchId;
#FXML
public TableColumn company;
#FXML
public TableColumn name;
#FXML
public TableColumn packing;
#FXML
public TableColumn quantity;
#FXML
public TableColumn expiry;
#FXML
public TableColumn mrp;
I'm guessing that you get NullPointerException in initalize() method when you try to setCellValueFactory() on table columns.
I assume that you are accessing fxml resource files correctly.

ListView built with SceneBuilder8 does not show inserted list

I am attempting to create a GUI for the front end of a program that will be used in my office. I have been tasked to use Scene Builder 8 to help create said GUI. This is my first project using JavaFX and Scene Builder so I've had to learn everything from scratch. My problem is that the while the code isn't throwing me any errors, I cannot see the sample data that I've put into the program. It's making me question the program as a whole.
If some of the following code looks superfluous to you, it may be because development for the backend part of the program is happening at the same time by a different person.
Here is the Mainapp:
package simit.gui;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import simit.gui.launch.model.LocalLaunch;
import simit.gui.launch.model.TextAreaOutputStream;
import simit.gui.launch.view.CompleteList;
import simit.gui.launch.view.LocalLaunchController;
import simit.gui.launch.view.MonitorController;
public class Main extends Application {
//Hold onto the main state
Stage primaryStage;
private ObservableList<simit.gui.launch.view.CompleteList> listData = FXCollections.observableArrayList();
public Main(){
listData.add(new CompleteList("sample1"));
listData.add(new CompleteList("sample2"));
}
public ObservableList<CompleteList> getListData(){
return listData;
}
//Run simulation
public void runSimulation(File inputDeck, int procs, int mem){
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("launch/view/Monitor.fxml"));
AnchorPane rootLayout = (AnchorPane) loader.load();
//Get the controller
MonitorController controller = loader.getController();
//Setup the view
List<TextAreaOutputStream> textAreas = controller.SetUpTextAreas(procs);
//Try to launch the code
LocalLaunch launch = new LocalLaunch(inputDeck, procs, mem, textAreas);
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
// try {
// BorderPane root = new BorderPane();
// Scene scene = new Scene(root,400,400);
// scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
// primaryStage.setScene(scene);
// primaryStage.show();
// } catch(Exception e) {
// e.printStackTrace();
// }
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("launch/view/LocalLaunch.fxml"));
AnchorPane rootLayout = (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
//Load up the LocalLaunch Controller
LocalLaunchController controller = loader.getController();
controller.SetMain(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Here is the FXML Controller:
package simit.gui.launch.view;
import java.io.File;
import org.controlsfx.control.CheckListView;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import simit.gui.Main;
import simit.gui.launch.model.LocalLaunch;
public class LocalLaunchController {
//Hold onto the required text fields
#FXML
private TextField path;
#FXML
private TextField procs;
#FXML
private TextField mem;
final ObservableList<CompleteList> items = FXCollections.observableArrayList();
#FXML
final public CheckListView<CompleteList> listItems = new CheckListView<CompleteList>();
private Main mainProgram;
public void SetMain(Main mainProgram){
this.mainProgram = mainProgram;
items.addAll(mainProgram.getListData());
listItems.setItems(items);
}
#FXML
private void handleSelect() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("SMT File", "*"+LocalLaunch.PaserExt),
new ExtensionFilter("Resume File", "*"+LocalLaunch.RsmExp),
new ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile != null) {
path.setText(selectedFile.getAbsolutePath());
}
}
#FXML
private void handleRun() {
//Make sure input is valid
if(!isInputValid())
return;
//Get the data
File tmpFile = new File(path.getText());
int proc = Integer.parseInt(procs.getText());
int mem = Integer.parseInt(this.mem.getText());
mainProgram.runSimulation(tmpFile, proc, mem);
}
/**
* Validates the user input in the text fields.
*
* #return true if the input is valid
*/
private boolean isInputValid() {
String errorMessage = "";
if(path.getText().isEmpty()){
errorMessage += "The input deck cannot be empty!\n";
}
//Create a test file
File testFile = new File(path.getText());
if(!testFile.exists())
errorMessage += "The input deck must exisit!\n";
if (procs.getText() == null || procs.getText().length() == 0) {
errorMessage += "No valid procs specified!\n";
} else {
// try to parse the postal code into an int.
try {
int p =Integer.parseInt(procs.getText());
if(p <= 0)
throw new NumberFormatException();
} catch (NumberFormatException e) {
errorMessage += "No valid procs specified (must be a positive integer)!\n";
}
}
if (mem.getText() == null || mem.getText().length() == 0) {
errorMessage += "No valid mem specified!\n";
} else {
// try to parse the postal code into an int.
try {
int p =Integer.parseInt(mem.getText());
if(p <= 0)
throw new NumberFormatException();
} catch (NumberFormatException e) {
errorMessage += "No valid mem specified (must be a positive integer)!\n";
}
}
if (errorMessage.length() == 0) {
return true;
} else {
// Show the error message.
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Invalid Fields");
alert.setHeaderText("Please correct invalid fields");
alert.setContentText(errorMessage);
alert.showAndWait();
return false;
}
}
#FXML
private void initialize() {
}
}
Here is a class I've made for the input variable:
package simit.gui.launch.view;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class CompleteList {
private final StringProperty listDetails;
public CompleteList(){
this(null);
}
public CompleteList(String listDetails){
this.listDetails = new SimpleStringProperty(listDetails);
}
public String getListDetails() {
return listDetails.get();
}
public void setListDetails(String listDetails) {
this.listDetails.set(listDetails);
}
public StringProperty listDetailsProperty(){
return listDetails;
}
}
And finally here is the FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.Cursor?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import org.controlsfx.control.*?>
<AnchorPane prefHeight="600.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="simit.gui.launch.view.LocalLaunchController">
<children>
<SplitPane dividerPositions="0.5" layoutX="120.0" layoutY="41.0" orientation="VERTICAL" prefHeight="600.0" prefWidth="400.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<ImageView fitWidth="600.0" pickOnBounds="true" preserveRatio="true" smooth="false">
<image>
<Image url="#../../resources/SIMITBlastLogo.png" />
</image>
<cursor>
<Cursor fx:constant="DEFAULT" />
</cursor>
</ImageView>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<GridPane layoutX="50.0" layoutY="58.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columnConstraints>
<ColumnConstraints fillWidth="false" hgrow="SOMETIMES" minWidth="10.0" prefWidth="20.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints fillWidth="false" hgrow="SOMETIMES" minWidth="10.0" prefWidth="0.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Label text="Input Deck">
<GridPane.margin>
<Insets left="10.0" />
</GridPane.margin></Label>
<Label text="Processors" GridPane.rowIndex="1">
<GridPane.margin>
<Insets left="10.0" />
</GridPane.margin></Label>
<TextField fx:id="procs" text="1" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextField fx:id="path" editable="false" GridPane.columnIndex="1" />
<Button alignment="CENTER_RIGHT" mnemonicParsing="false" onAction="#handleSelect" text="Select" GridPane.columnIndex="2" GridPane.halignment="CENTER" GridPane.valignment="CENTER">
<GridPane.margin>
<Insets />
</GridPane.margin>
</Button>
<Label text="Mem/Proc" GridPane.rowIndex="2">
<GridPane.margin>
<Insets left="10.0" />
</GridPane.margin></Label>
<Label text="GB" GridPane.columnIndex="2" GridPane.rowIndex="2" />
<TextField fx:id="mem" promptText="1" text="1" GridPane.columnIndex="1" GridPane.rowIndex="2" />
</children>
</GridPane>
<ButtonBar layoutX="129.0" layoutY="248.0" prefHeight="40.0" prefWidth="200.0" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0">
<buttons>
<Button defaultButton="true" mnemonicParsing="false" onAction="#handleRun" text="Run Simulation" />
</buttons>
</ButtonBar>
<CheckListView fx:id="listItems" layoutX="200.0" layoutY="117.0" prefHeight="200.0" prefWidth="200.0" />
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>
Here is what I'm seeing when I run the program (minus the image on top, I've gotten rid of it for a little anonymity):
Image of the program when ran.
What I need to see is list items populating that white square in the middle.
Any help anyone can give me at all would be greatly appreciated.

Resources