I'm trying to make a program which gets data from textfield, adds it to tableview and then to DB. The problem is, that I also need a tableview to accept an empty textfield value.
This is how I add values to the tableview:
public void pievButtonClicked() {
int kods = Integer.parseInt(kodsT.getText());
String nosaukums = nosaukumsT.getText();
int inventars = Integer.parseInt(iegadesT.getText());
double uzskaite = Double.parseDouble(uzskaitesT.getText());
double iegade = Double.parseDouble(iegadesT.getText());
data.addAll(new Interjers(kods, nosaukums, inventars, uzskaite, iegade));
}
Maybe I need to change "Interijers" class or I need to change setCellValueFactory is some way. I really don't know.
I don't know what do want exactly ! but i made this example for you ,it seems explain your need
Model class:
package javafxapplication4;
public class Model {
String name;
String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public Model(String name, String age) {
this.name = name;
this.age = age;
}
public void setAge(String age) {
this.age = age;
}
}
Fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.URL?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.111" fx:controller="javafxapplication4.HomeController">
<stylesheets>
<URL value="#home.css" />
</stylesheets>
<children>
<TextField fx:id="nameField" layoutY="30.0" />
<TextField fx:id="ageField" layoutX="226.0" layoutY="30.0" />
<Button layoutX="451.0" layoutY="30.0" mnemonicParsing="false" onAction="#addLine" text="Button" />
<TableView fx:id="view" layoutX="52.0" layoutY="100.0" prefHeight="200.0" prefWidth="506.0">
<columns>
<TableColumn fx:id="nameCo" prefWidth="75.0" text="Name" />
<TableColumn fx:id="ageCo" prefWidth="75.0" text="Age" />
</columns>
</TableView>
</children>
</AnchorPane>
Controller class :
package javafxapplication4;
/*
* 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.
*/
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author Ala_Eddine
*/
public class HomeController implements Initializable {
/**
* Initializes the controller class.
*/
#FXML
public TableView<Model> view;
#FXML
public TableColumn<Model, String> nameCo;
#FXML
public TableColumn<Model, String> ageCo;
#FXML
public TextField nameField;
#FXML
public TextField ageField;
#Override
public void initialize(URL url, ResourceBundle rb) {
nameCo.setCellValueFactory(new PropertyValueFactory<>("name"));
ageCo.setCellValueFactory(new PropertyValueFactory<>("age"));
}
#FXML
public void addLine() {
String name = nameField.getText();
String age = ageField.getText();
Model model = new Model(name, age);
view.getItems().add(model);
}
}
Main class:
/*
* 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 javafxapplication4;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author Ala_Eddine
*/
public class JavaFXApplication4 extends Application {
#Override
public void start(Stage primaryStage) throws IOException {
Stage stage=new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Home.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);
}
}
Result
Related
I'm trying to get a TableView TextFieldTableCell to be both wrapping the text and adjusting the cell height and also be editable at the same time.
So i'm able to make it wrapped or editable, but not at the same time.
I have been following this Thread and trying about a 100 different permutations and possibilities. I'm sure it is possible, but i'm reaching full fustration quickly. So any help would be highly appreciated!
I'm using SceneBuilder and importing the handles. MainFX.fxml: -->
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.StackPane?>
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="wrappingEditableCellProject.Controller">
<children>
<AnchorPane prefHeight="200.0" prefWidth="200.0">
<children>
<TableView fx:id="tableView" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="id" prefWidth="75.0" text="id" />
<TableColumn fx:id="name" prefWidth="75.0" text="name" />
</columns>
</TableView>
</children>
</AnchorPane>
</children>
</StackPane>
My Main class:
package wrappingEditableCellProject;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main (String[] args) {
// TODO Auto-generated method stub
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MainFX.fxml"));
primaryStage.setTitle("mainFx");
primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.show();
}
}
My data entry class:
package wrappingEditableCellProject;
public class TableEntry {
private int id;
private String name;
public TableEntry (int id, String name){
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Controller class:
package wrappingEditableCellProject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.converter.IntegerStringConverter;
public class Controller {
#FXML TableView<TableEntry> tableView;
#FXML TableColumn<TableEntry, Integer> id;
#FXML TableColumn<TableEntry, String> name;
private ObservableList<TableEntry> dataList = FXCollections.observableArrayList();
#SuppressWarnings({ "rawtypes", "unchecked" })
public void initialize(){
// Set editable
tableView.setEditable(true);
// Configure columns
id.setCellValueFactory(new PropertyValueFactory<>("id"));
id.setCellFactory(TextFieldTableCell.<TableEntry, Integer>forTableColumn(new IntegerStringConverter()));
id.setStyle("-fx-alignment: CENTER-LEFT;");
id.setEditable(false);
id.setSortable(false);
name.setCellValueFactory(new PropertyValueFactory<>("name"));
name.setCellFactory(WrappingTextFieldTableCell.<TableEntry>forTableColumn());
name.setStyle("-fx-alignment: CENTER-LEFT;");
name.setSortable(false);
name.setOnEditCommit(evt -> {
System.out.println("Edit comitted");
evt.getRowValue().setName(evt.getNewValue());
});
TableColumn[] tableColumns = {id,name};
tableView.getColumns().clear();
tableView.getColumns().addAll(tableColumns);
// add data to the table
dataList.clear();
dataList.add(new TableEntry(1, "Steve Upperton Stevenson"));
dataList.add(new TableEntry(2, "Peter May Parker"));
dataList.add(new TableEntry(3, "Tony Stark the machinist"));
dataList.add(new TableEntry(4, "Pepper Pots the CEO of Stark industies"));
FilteredList<TableEntry> dataFiltered = new FilteredList<>(dataList, b -> true);
SortedList<TableEntry> dataSorted = new SortedList<>(dataFiltered);
dataSorted.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(dataSorted);
}
}
Here is my custom cell class WrappingTextFieldTableCell:
package wrappingEditableCellProject;
import javafx.scene.control.Control;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.text.Text;
import javafx.util.converter.DefaultStringConverter;
public class WrappingTextFieldTableCell<S> extends TextFieldTableCell<S, String> {
private final Text cellText;
public WrappingTextFieldTableCell() {
super(new DefaultStringConverter());
setPrefHeight(Control.USE_COMPUTED_SIZE);
this.cellText = createText();
}
#Override
public void cancelEdit() {
super.cancelEdit();
setGraphic(cellText);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!isEmpty() && !isEditing()) {
setGraphic(cellText);
}
}
private Text createText() {
Text text = new Text();
text.wrappingWidthProperty().bind(widthProperty());
text.textProperty().bind(itemProperty());
return text;
}
}
This solution allows me to edit the cell(I know there are easier ways for this), but the wrapping is not taking.
As mentioned i have tried 100 different ways to approach this challenge, but i think this would be the easiest to relate to for any assistance.
Thanks for any support!
I am trying to populate tables in separate tabs in TabPane.
I was able to populate only the one in first tab like this:
#FXML
public void initialize(URL url, ResourceBundle rb) {
//assert serviceChoiceBox1 != null : "fx:id=\"serviceChoiceBox1\" was not injected: check your FXML file 'ScheduleServicePane.fxml'.";
ServiceName.setCellValueFactory(new PropertyValueFactory<Service, String>("name"));
ServicePrice.setCellValueFactory(new PropertyValueFactory<Service, Double>("price"));
ServiceDuration.setCellValueFactory(new PropertyValueFactory<Service, Integer>("duration"));
TableView.setItems(List());
}
private ObservableList<Service> List(){
ObservableList<Service> service = FXCollections.observableArrayList(serviceRepository.list());
return service;
}
I have two more tabs with tables but somehow I am not able to fill them with prepared list of data that I have
I want to populate other tabs with similar data
Anyone can help?
I also read about separate Controllers for each tab but this seems to be to much in such a case.
I would use FilteredList in this case. This will allow you to create "sublist" of the original list. In this demo, I create a "type" field in the Service class. I then filter the original list based on the "type". You don't have to create a "type" field, but you will need to find something to filter on if you don't.
Main:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication184 extends Application
{
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.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);
}
}
Controller:
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
/**
*
* #author blj0011
*/
public class FXMLDocumentController implements Initializable
{
#FXML
private TabPane tpMain;
#FXML
private TableView<Service> tvTab1, tvTab2;
#FXML
private TableColumn<Service, String> tcServiceNameTab1, tcServicePriceTab1, tcServiceDurationTab1;
#FXML
private TableColumn<Service, String> tcServiceNameTab2, tcServicePriceTab2, tcServiceDurationTab2;
#FXML
private void handleButtonAction(ActionEvent event)
{
System.out.println("You clicked me!");
}
#Override
public void initialize(URL url, ResourceBundle rb)
{
tcServiceNameTab1.setCellValueFactory(new PropertyValueFactory("name"));
tcServicePriceTab1.setCellValueFactory(new PropertyValueFactory("price"));
tcServiceDurationTab1.setCellValueFactory(new PropertyValueFactory("duration"));
tcServiceNameTab2.setCellValueFactory(new PropertyValueFactory("name"));
tcServicePriceTab2.setCellValueFactory(new PropertyValueFactory("price"));
tcServiceDurationTab2.setCellValueFactory(new PropertyValueFactory("duration"));
//Add sanoke data
List<Service> services = new ArrayList();
services.add(new Service("Manicure 1", "40.0", "60", "Manicure"));
services.add(new Service("Manicure 2", "40.0", "60", "Manicure"));
services.add(new Service("Pedicure 1", "40.0", "60", "Pedicure"));
services.add(new Service("Pedicure 2", "40.0", "60", "Pedicure"));
FilteredList<Service> flTab1 = new FilteredList(FXCollections.observableArrayList(services), getManicures());
FilteredList<Service> flTab2 = new FilteredList(FXCollections.observableArrayList(services), getPedicures());
tvTab1.setItems(flTab1);
tvTab2.setItems(flTab2);
}
Predicate<Service> getManicures()
{
return p -> p.getType().equals("Manicure");
}
Predicate<Service> getPedicures()
{
return p -> p.getType().equals("Pedicure");
}
}
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="406.0" prefWidth="369.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.141" fx:controller="javafxapplication184.FXMLDocumentController">
<children>
<TabPane fx:id="tpMain" layoutX="56.0" layoutY="67.0" prefHeight="200.0" prefWidth="200.0" tabClosingPolicy="UNAVAILABLE" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<tabs>
<Tab text="Manicure">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<TableView fx:id="tvTab1" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="tcServiceNameTab1" prefWidth="75.0" text="Service" />
<TableColumn fx:id="tcServicePriceTab1" prefWidth="75.0" text="Price" />
<TableColumn fx:id="tcServiceDurationTab1" prefWidth="75.0" text="Duration" />
</columns>
</TableView>
</children>
</AnchorPane>
</content>
</Tab>
<Tab text="Pedicure">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<TableView fx:id="tvTab2" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="tcServiceNameTab2" prefWidth="75.0" text="Service" />
<TableColumn fx:id="tcServicePriceTab2" prefWidth="75.0" text="Price" />
<TableColumn fx:id="tcServiceDurationTab2" prefWidth="75.0" text="Duration" />
</columns>
</TableView>
</children>
</AnchorPane>
</content>
</Tab>
</tabs>
</TabPane>
</children>
</AnchorPane>
Service:
/**
*
* #author blj0011
*/
public class Service
{
private String name;
private String price;
private String duration;
private String type;
public Service(String name, String price, String duration, String type)
{
this.name = name;
this.price = price;
this.duration = duration;
this.type = type;
}
/**
* #return the name
*/
public String getName()
{
return name;
}
/**
* #param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* #return the price
*/
public String getPrice()
{
return price;
}
/**
* #param price the price to set
*/
public void setPrice(String price)
{
this.price = price;
}
/**
* #return the duration
*/
public String getDuration()
{
return duration;
}
/**
* #param duration the duration to set
*/
public void setDuration(String duration)
{
this.duration = duration;
}
/**
* #return the type
*/
public String getType()
{
return type;
}
/**
* #param type the type to set
*/
public void setType(String type)
{
this.type = type;
}
}
I have a very strange problem with my test application. I need to fill the JavaFX TableView element with some data. Here is the code:
fxmldocumentController.java
import java.net.URL;
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.TableView; //A
import javafx.scene.control.TableColumn; //B
import javafx.scene.control.cell.PropertyValueFactory; //C
public class fxmldocumentController implements Initializable
{
#FXML
private TableView<employees> mainTableView;
#FXML
private TableColumn<employees, Integer> age;
#FXML
private TableColumn<employees, String> userName, companyName;
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO:
mainTableView.getItems().
add(new employees("Yuri P. Bodrov", "VMware", 35));
mainTableView.getItems().
add(new employees("Ivan Y. Bodrov", "VMware", 5));
mainTableView.getItems().
add(new employees("Peter Y. Bodrov", "VMware", 2));
// A problem starts here:
age.setCellValueFactory(new PropertyValueFactory<>("age"));
userName.setCellValueFactory(new PropertyValueFactory<>("userName"));
companyName.
setCellValueFactory(new PropertyValueFactory<>("companyName"));
}
}
fxmldocument.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="300.0" prefWidth="400.0" style="-fx-
background-color: white;"
xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sampletableviewapp00.fxmldocumentController">
<children>
<Label fx:id="testLabel" layoutX="14.0" layoutY="14.0" style="-fx-
background-color: white;" text="Employees. TableView." textFill="#505050">
<font>
<Font size="14.0" />
</font>
</Label>
<TableView fx:id="mainTableView" layoutX="12.0" layoutY="50.0"
prefHeight="200.0" prefWidth="377.0">
<columns>
<TableColumn prefWidth="90.0" text="UserName" />
<TableColumn prefWidth="119.0" text="CompanyName" />
<TableColumn prefWidth="84.0" text="Age" />
</columns>
</TableView>
</children>
</AnchorPane>
Sampletableviewapp00.java
package sampletableviewapp00;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Sampletableviewapp00 extends Application
{
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load(getClass().
getClassLoader().getResource("fxmldocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
employees.java
package sampletableviewapp00;
public class employees
{
String userName, companyName;
int age;
// Generate Properties. Getters:
public int GetAge()
{
return age;
}
public String GetUserName()
{
return userName;
}
public String GetCompanyName()
{
return companyName;
}
// Generate Properties. Setters:
public void SetAge(int age)
{
this.age = age;
}
public void SetUserName(String userName)
{
this.userName = userName;
}
public void SetCompanyName(String companyName)
{
this.companyName = companyName;
}
// Generate Constructor of Employees class:
public employees(String userName, String companyName, int age)
{
this.userName = userName;
this.companyName = companyName;
this.age = age;
}
}
When I run this application the NetBeans IDE 8.2 returns this stack of exceptions/errors: see outputError.png as attachment
outputError.png
outputError02.PNG
Dear colleagues! Do you have any ideas to resolve this problem? Could you try to write this code by yourself and run? Thanks in advance! :-)
You have fxmldocument.xml but tried to load "fxmldocument.fxml".
Rename the file to have fxml extension.
Also make sure you put the fxml file under /resources/yourpackagepath/ folder and load as:
Sampletableviewapp00.class.getResource("fxmldocument.fxml")
This line is triggering the exception:
Parent root = FXMLLoader.load(getClass().
getClassLoader().getResource("fxmldocument.fxml"));
Your fxml document's extension is xml in your project and you are trying to load it as .fxml in the above line.
Rename fxmldocument.xml to fxmldocument.fxml.
I keep on searching for an answer but still I can't find the right way to do it (or probably the mistakes in my codes). I am using javafx with scenebuilder. mySQL is the database that I am using. help please :(
package cedproject;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import java.sql.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
/**
* FXML Controller class
*
* #author My Lightstream
*/
public class FXMLController implements Initializable {
public java.sql.PreparedStatement ps;
public java.sql.ResultSet rs;
#FXML
private AnchorPane donationWindow;
//#FXML
//private TableView<?> tblView;
#FXML
TableView<userdata> tblView= new TableView<>();
#FXML
private TableColumn<?, ?> colOR;
#FXML
private TableColumn<?, ?> colAmount;
#FXML
private Button btnNew;
#FXML
private TextField txtSearch;
private static java.sql.Connection con;
private static Statement stat;
private PreparedStatement prep;
private ObservableList<userdata> data;
#FXML
private Button btnLoad;
#FXML
private Group gp;
// </userdata>
/**
#FXML
private Button btnNew;
#FXML
private AnchorPane donationWindow;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
try{
ps = new Connect().connectDatabase();
ps.execute();
tblView.getItems().setAll(this.data);
}catch(Exception e){
}
lagay();
}
public void lagay(){
try{
String query = "select * from receipt";
tblView.getItems().clear();
ps = con.prepareStatement("select * from receipt");
rs = ps.executeQuery(query);
}catch(Exception e){
System.out.println("mali ka shunga");
}
ObservableList<userdata> data = FXCollections.observableArrayList();
try{
while(rs.next()){
data.add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));}
}catch(Exception e){}
}
public void tableView()throws Exception{
tblView.getItems().clear();
rs = ps.executeQuery("SELECT ORNUM,AMOUNT FROM RECEIPT");
ObservableList<userdata> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ORNUM");
column1.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("ornum"));
TableColumn column2 = new TableColumn("Amount");
column2.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("amount"));
tblView.getColumns().addAll(column1,column2);
tblView.getChildrenUnmodifiable();
}
#FXML
public void handleButtonAction2(ActionEvent event) {
}
#FXML
public void activated(MouseEvent event) {
}
private void onClicked(ActionEvent event) throws SQLException {
/* tblView.getItems().clear();
rs = ps.executeQuery("SELECT ORNUM,AMOUNT FROM RECEIPT");
ObservableList<userdata> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ORNUM");
column1.setCellValueFactory(new PropertyValueFactory<>("ORNUM"));
TableColumn column2 = new TableColumn("Amount");
column2.setCellValueFactory(new PropertyValueFactory<>("Amount"));
tblView.getColumns().addAll(column1,column2);*/
ObservableList<userdata> data = FXCollections.observableArrayList();
try{ String query = "select * from receipt";
tblView.getItems().clear();
ps = con.prepareStatement(query);
rs = ps.executeQuery("SELECT * from receipt");
while(rs.next()){
tblView.getItems().add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));
tblView.setItems(data);
}
ps.close();
rs.close();
}catch(Exception e){
}
}
#FXML
private void onClicked(MouseEvent event) throws Exception {
System.out.println("gawin mo");
ObservableList<userdata> data = FXCollections.observableArrayList();
System.out.println("ginawa");
tableView();
try{
String query = "select * from receipt";
tblView.getItems().clear();
ps = new Connect().connectDatabase();
ps = new Connect().connectDatabase();
rs = ps.executeQuery(query);
while(rs.next()){
tblView.getItems().add(new userdata(
rs.getInt("ORNUM"),
rs.getInt("AMOUNT")
));
tblView.setItems(data);
}
}catch(Exception e){
System.out.print("asdqweasd");
}
}
/**
*
* #param event
*/
/* #FXML
public void konekplis(SortEvent<C> event) {
}*/
}
package cedproject;
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;
/**
*enter code here
* #author My Lightstream
*/
public class userdata {
public SimpleIntegerProperty Ornum;
public SimpleIntegerProperty Amount;
public userdata(Integer ornum, Integer amount) {
this.Ornum = new SimpleIntegerProperty(ornum);
this.Amount = new SimpleIntegerProperty(amount);
}
userdata(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
userdata(String string, String string0, String string1, String string2, String string3, String string4) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Integer getOrnum() {
return Ornum.get();
}
public Integer getAmount() {
return Amount.get();
}
public void setOrnum(Integer ornum) {
this.Ornum.set(ornum);
}
public void setAmount(Integer amount) {
this.Amount.set(amount);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.effect.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" fx:id="donationWindow" onDragDetected="#activated" prefHeight="482.0" prefWidth="696.0" styleClass="mainFxmlClass" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cedproject.FXMLController">
<stylesheets>
<URL value="#fxml.css" />
</stylesheets>
<children>
<AnchorPane layoutY="8.0" prefHeight="482.0" prefWidth="696.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<TableView fx:id="tblView" layoutX="21.0" layoutY="87.0" prefHeight="181.0" prefWidth="655.0">
<columns>
<TableColumn fx:id="colOR" prefWidth="326.0" text="OR Number" />
<TableColumn fx:id="colAmount" prefWidth="325.0" text="Amount" />
</columns>
</TableView>
<Button fx:id="btnNew" layoutX="500.0" layoutY="35.0" mnemonicParsing="false" onAction="#handleButtonAction2" prefHeight="25.0" prefWidth="78.0" text="NEW" />
<Button layoutX="587.0" layoutY="35.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="78.0" text="EDIT" />
<TextField fx:id="txtSearch" layoutX="40.0" layoutY="35.0" prefHeight="25.0" prefWidth="204.0" promptText="Search" />
<TextArea editable="false" layoutX="19.0" layoutY="336.0" prefHeight="132.0" prefWidth="655.0">
<effect>
<DropShadow height="14.0" radius="6.5" width="14.0" />
</effect>
</TextArea>
<Label layoutX="26.0" layoutY="305.0" prefHeight="17.0" prefWidth="68.0" text="Description:" />
<Button fx:id="btnLoad" layoutX="424.0" layoutY="35.0" mnemonicParsing="false" onMouseClicked="#onClicked" prefHeight="25.0" prefWidth="68.0" text="Load" />
<Group fx:id="gp" />
</children>
<cursor>
<Cursor fx:constant="DEFAULT" />
</cursor>
</AnchorPane>
</children>
</AnchorPane>
Please help :(
I currently using afterburner.fx to tailor together components of JavaFX based application.
Right now I trying move components in separate fxml files for more comfortable maintenance.
To load such components I using fx:include directive which allow load nested components automatically.
Problem is that with automatic load I loosing possibility get presenter from nested view.
Is there a way to combine automatic load and in same time, be able work with nested components from parent root?
These two seem to work fine together.
Afterburner works by setting a controller factory on the FXML loader, which takes care of instantiating the presenter class and injecting values into it.
The <fx:include> element will propagate the controller factory when loading the included FXML, so you can also inject values into the controller defined in the included FXML. Because afterburner effectively uses a singleton scope for injection, the same instance of injected fields will be used. This means you can readily share your data model between the different presenter classes.
If you want access to the presenter associated with the included FXML, just use the standard technique for "nested controllers".
So, for example:
main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.geometry.Insets?>
<BorderPane xmlns:fx="http://javafx.com/fxml" fx:controller="application.MainPresenter">
<center>
<TableView fx:id="table">
<columns>
<TableColumn text="First Name" prefWidth="150">
<cellValueFactory>
<PropertyValueFactory property="firstName" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Last Name" prefWidth="150">
<cellValueFactory>
<PropertyValueFactory property="lastName" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Email" prefWidth="200">
<cellValueFactory>
<PropertyValueFactory property="email" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
</center>
<bottom>
<fx:include source="Editor.fxml" fx:id="editor">
<padding>
<Insets top="5" bottom="5" left="5" right="5"/>
</padding>
</fx:include>
</bottom>
</BorderPane>
editor.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Button?>
<GridPane xmlns:fx="http://javafx.com/fxml" hgap="5" vgap="10" fx:controller="application.EditorPresenter">
<Label GridPane.rowIndex="0" GridPane.columnIndex="0" text="First Name:"/>
<TextField fx:id="firstNameTextField" GridPane.rowIndex="0" GridPane.columnIndex="1"/>
<Label GridPane.rowIndex="1" GridPane.columnIndex="0" text="Last Name"/>
<TextField fx:id="lastNameTextField" GridPane.rowIndex="1" GridPane.columnIndex="1"/>
<Label GridPane.rowIndex="2" GridPane.columnIndex="0" text="Email"/>
<TextField fx:id="emailTextField" GridPane.rowIndex="2" GridPane.columnIndex="1"/>
<HBox GridPane.rowIndex="3" GridPane.columnIndex="0" GridPane.columnSpan="2">
<Button fx:id="addEditButton" onAction="#addEdit" />
</HBox>
</GridPane>
MainPresenter.java:
package application;
import javax.inject.Inject;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
public class MainPresenter {
#FXML
private TableView<Person> table ;
// This is the controller (presenter) for the included fxml
// It is injected by the FXMLLoader; the rule is that "Controller" needs to be
// appended to the fx:id attribute of the <fx:include> tag.
// This is not used in this example but is here to demonstrate how to access it
// if needed.
#FXML
private EditorPresenter editorController ;
#Inject
private DataModel dataModel ;
public void initialize() {
table.setItems(dataModel.getPeople());
table.getSelectionModel().selectedItemProperty().addListener(
(obs, oldPerson, newPerson) -> dataModel.setCurrentPerson(newPerson));
dataModel.currentPersonProperty().addListener((obs, oldPerson, newPerson) -> {
if (newPerson == null) {
table.getSelectionModel().clearSelection();
} else {
table.getSelectionModel().select(newPerson);
}
});
dataModel.getPeople().addAll(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com")
);
}
}
EditorPresenter.java:
package application;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javax.inject.Inject;
public class EditorPresenter {
#FXML
private TextField firstNameTextField ;
#FXML
private TextField lastNameTextField ;
#FXML
private TextField emailTextField ;
#FXML
private Button addEditButton ;
#Inject
private DataModel dataModel ;
public void initialize() {
addEditButton.textProperty().bind(
Bindings.when(Bindings.isNull(dataModel.currentPersonProperty()))
.then("Add")
.otherwise("Update")
);
dataModel.currentPersonProperty().addListener((obs, oldPerson, newPerson) -> {
if (newPerson == null) {
firstNameTextField.setText("");
lastNameTextField.setText("");
emailTextField.setText("");
} else {
firstNameTextField.setText(newPerson.getFirstName());
lastNameTextField.setText(newPerson.getLastName());
emailTextField.setText(newPerson.getEmail());
}
});
}
#FXML
private void addEdit() {
Person person = dataModel.getCurrentPerson();
String firstName = firstNameTextField.getText();
String lastName = lastNameTextField.getText();
String email = emailTextField.getText();
if (person == null) {
dataModel.getPeople().add(new Person(firstName, lastName, email));
} else {
person.setFirstName(firstName);
person.setLastName(lastName);
person.setEmail(email);
}
}
}
MainView.java:
package application;
import com.airhacks.afterburner.views.FXMLView;
public class MainView extends FXMLView {
}
Main.java (application class):
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import com.airhacks.afterburner.injection.Injector;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
MainView mainView = new MainView();
Scene scene = new Scene(mainView.getView(), 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
#Override
public void stop() throws Exception {
Injector.forgetAll();
}
public static void main(String[] args) {
launch(args);
}
}
DataModel.java:
package application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class DataModel {
private final ObservableList<Person> people = FXCollections.observableArrayList();
private final ObjectProperty<Person> currentPerson = new SimpleObjectProperty<>(this, "currentPerson");
public ObservableList<Person> getPeople() {
return people ;
}
public final Person getCurrentPerson() {
return currentPerson.get();
}
public final void setCurrentPerson(Person person) {
this.currentPerson.set(person);
}
public ObjectProperty<Person> currentPersonProperty() {
return currentPerson ;
}
}
And the usual Person.java example:
package application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Person {
private final StringProperty firstName = new SimpleStringProperty(this, "firstName");
public final String getFirstName() {
return firstName.get();
}
public final void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName ;
}
private final StringProperty lastName = new SimpleStringProperty(this, "lastName");
public final String getLastName() {
return lastName.get();
}
public final void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName ;
}
private final StringProperty email = new SimpleStringProperty(this, "email");
public final String getEmail() {
return email.get();
}
public final void setEmail(String email) {
this.email.set(email);
}
public StringProperty emailProperty() {
return email ;
}
public Person(String firstName, String lastName, String email) {
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
}
}