I created a table view, linked it with my model and put into fxml like this:
Main.java
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("table.fxml"));
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java
public class Controller {
#FXML
private javafx.scene.control.TableView<TableView> tableView;
#FXML
public void initialize() {
ObservableList<TableView> data = tableView.getItems();
data.add(new TableView("Item1", true));
data.add(new TableView("Item2", false));
}
}
TableView.java
public class TableView {
private SimpleStringProperty text;
private SimpleBooleanProperty check;
TableView(String text, boolean check) {
this.text = new SimpleStringProperty(text);
this.check = new SimpleBooleanProperty(check);
}
public boolean getCheck() {
return check.get();
}
public SimpleBooleanProperty checkProperty() {
return check;
}
public void setCheck(boolean check) {
this.check.set(check);
}
public String getText() {
return text.get();
}
public SimpleStringProperty textProperty() {
return text;
}
public void setText(String text) {
this.text.set(text);
}
}
CheckBoxTableCellFactory.java
public class CheckBoxTableCellFactory<S, T> implements Callback<TableColumn<S, T>, TableCell<S, T>> {
public TableCell<S, T> call(TableColumn<S, T> param) {
return new CheckBoxTableCell<>();
}
}
table.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import table.CheckBoxTableCellFactory?>
<VBox prefHeight="600.0" prefWidth="900.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="table.Controller">
<SplitPane focusTraversable="true" VBox.vgrow="ALWAYS">
<Pane prefHeight="200.0" prefWidth="200.0">
<TableView fx:id="tableView" layoutX="6.0" layoutY="4.0" prefHeight="406.0" prefWidth="694.0">
<columns>
<TableColumn prefWidth="75.0" text="Check">
<cellValueFactory>
<PropertyValueFactory property="check" />
</cellValueFactory>
<cellFactory>
<CheckBoxTableCellFactory />
</cellFactory>
</TableColumn>
<TableColumn prefWidth="200.0" text="Text">
<cellValueFactory>
<PropertyValueFactory property="text"/>
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
</Pane>
</SplitPane>
</VBox>
I looks good -
screenshot
but checkboxes are disabled - I cannot check/un-check them. When I click on them, they don't change their state (checked/un-checked). How to fix it?
By default, a TableView is not editable meaning any custom controls within the TableView are also disabled.
You can enable editing by either updating your FXML definition of the TableView to include editable="true" or in your controller with tableView.setEditable(true);.
Related
I have two controllers:
Main which contains TableView Tab which displays SQLITE database tables (which contain different number of columns) in tabular format, and
Rem which contains a button which dictates which database to display (there are many such controllers).
Now if I create a method in Main which is responsible for updating and displaying TableView contents, how do I use that method in other controller?
I created two static ObservableList variables columns and rows and bind them to Tab in Main's initialize.
APP.java
public class App extends Application {
private static Scene scene;
public static Connection conn;
#Override
public void start(Stage stage) throws IOException {
try{
conn=java.sql.DriverManager.getConnection("jdbc:sqlite:sample.db");
if(conn!=null){
conn.createStatement().execute("CREATE TABLE IF NOT EXISTS tab1(Field0 TEXT, Field1 TEXT, Field2 TEXT);");
conn.createStatement().execute("CREATE TABLE IF NOT EXISTS tab2(Field3 TEXT, Field4 TEXT);");
}
}catch(Exception ex){
System.out.println(ex);
}
scene = new Scene(loadFXML("main"), 640, 480);
stage.setScene(scene);
stage.show();
}
private static Parent loadFXML(String fxml) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
return fxmlLoader.load();
}
public static void main(String[] args) {
launch();
}
public static ResultSet getRS(String table){
String sql="SELECT * FROM "+table;
ResultSet rs=null;
try{
rs=conn.createStatement().executeQuery(sql);
}catch(Exception ex){
System.out.println(ex);
}
return rs;
}
}
MAIN.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.TableView?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx/19" xmlns:fx="http://javafx.com/fxml/1" fx:controller="nic.testfx.Main">
<children>
<MenuBar>
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" onAction="#loadRem" text="Load Remaining" />
</items>
</Menu>
</menus>
</MenuBar>
<TableView fx:id="Tab" prefHeight="200.0" prefWidth="200.0" />
<VBox fx:id="remPane" prefHeight="200.0" prefWidth="100.0" />
</children>
</VBox>
MAIN.JAVA
public class Main implements Initializable {
#FXML
public TableView<ObservableList<String>> Tab;
#FXML
private VBox remPane;
#Override
public void initialize(URL url, ResourceBundle rb) {
Tab.itemsProperty().bind(getTabRow());
}
public void makeTable(ResultSet rs){
try{
var rsm=rs.getMetaData();
ObservableList<TableColumn<ObservableList<String>,String>>cols=FXCollections.observableArrayList();
for(int i=0;i<rsm.getColumnCount();i++){
final int j=i;
TableColumn<ObservableList<String>,String> col=new TableColumn(rsm.getColumnName(i+1));
col.setCellValueFactory(param->new SimpleStringProperty(param.getValue().get(j)));
cols.add(col);
}
ObservableList<ObservableList<String>> arows=FXCollections.observableArrayList();
while(rs.next()){
ObservableList<String> row=FXCollections.observableArrayList();
for(int i=1;i<=rsm.getColumnCount();i++){
row.add(rs.getString(i));
}
arows.add(row);
}
setTable(cols,arows);
}catch(Exception ex){
System.out.println(ex);
}
}
private static final ObservableList<TableColumn<ObservableList<String>,String>> columns=FXCollections.observableArrayList();
private static final javafx.beans.property.ListProperty<ObservableList<String>> rows=new javafx.beans.property.SimpleListProperty();
private javafx.beans.property.ListProperty getTabRow(){
Tab.getColumns().clear();
Tab.getColumns().addAll(columns);
return rows;
}
private static void setTable(ObservableList<TableColumn<ObservableList<String>,String>>c,ObservableList<ObservableList<String>> r){
columns.setAll(c);
rows.set(r);
}
#FXML
private void loadRem(ActionEvent event) {
try{
for(int i=remPane.getChildren().size()-1;i>=0;i--){
remPane.getChildren().remove(i);
}
javafx.fxml.FXMLLoader fxmlLoader=new javafx.fxml.FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("rem.fxml"));
javafx.scene.layout.Pane panel=fxmlLoader.load();
remPane.getChildren().add(panel);
makeTable(App.getRS("tab1"));
}catch(Exception ex){
System.out.println(ex);
}
}
}
REM.FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>
<VBox alignment="CENTER" xmlns="http://javafx.com/javafx/19" xmlns:fx="http://javafx.com/fxml/1" fx:controller="nic.testfx.Rem">
<children>
<Button fx:id="btn" mnemonicParsing="false" onAction="#loadTab" text="Button" />
</children>
</VBox>
REM.JAVA
public class Rem implements Initializable {
#FXML
private Button btn;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void loadTab(ActionEvent event) {
try{
var fxml=new javafx.fxml.FXMLLoader(App.class.getResource("main.fxml"));
fxml.load();
Main controller=fxml.getController();
var rs=App.getRS("tab2");
controller.makeTable(rs);
}catch(Exception ex){
System.out.println(ex);
}
}
}
OK I got it.
Created a java class which encapsulate method makeTable:
MODEL.JAVA
public class Model{
private final TableView table;
public Model(TableView t){
this.table=t;
}
public void makeTable(ResultSet rs){
ObservableList<TableColumn<ObservableList<String>,String>>tabcols=FXCollections.observableArrayList();
ObservableList<ObservableList<String>>tabrows=FXCollections.observableArrayList();
//Create TableColumns and add to tabcols;
while(rs.next()){
//Create ObservableList<String>, get data from rs, and add to tabrows
}
this.table.getColumns().setAll(tabcols);
this.table.getItems().setAll(tabrows);
}
}
Next, in Controller file Main.java created a static instance of Model:
MAIN.JAVA
public class Main implements Initializable{
#FXML
private TableView<ObservableList<String>> Tab;
static Model model;
#Override
public void initialize (URL url, ResourceBundle rb){
model=new Model(Tab);
}
}
Now I can use model from Rem controller:
REM.JAVA
public class Rem implements Initializable{
#FXML
private Button btn;
#Override
public void initialize (URL url, ResourceBundle rb){
//TODO
}
#FXML
private void loadTab(ActionEvent event){
var rs=App.getRS("tab2");
Main.model.makeTable(rs);
}
What i need:
Need an editable combobox which filters the data on the popup upon typing and first matching item should be highlighted and should set as the text in the combo upon pressing enter.
The popup should be a tableview with 2 or 3 columns. (screen shot attached.)(in the image it is a textfield but i prefer combo so that if the user is not sure about the values, he can click the combo button and see the entire list and select one.)
I will be binding some data as a source to the tableview which should act as the popup for the combobox.
I know i should go for a custom control but dont know where to start?
Reference URL: enter link description here
Thanks in Advance.
What i have tried so far:
Guys,
With the idea you guys gave, I have tried this so far and able to achieve.
(For now, i am not showing the tableview dynamically below the text field (eventually dats wat i want))
1. A tableview with static data is already loaded and added to the scene.
2. Having a text field below the tableview. (this is named as txt)
3. Having another text field below the first text field(this is named as txt1) (when i press tab from the previous text field cursor should come here)
i have a predicate set for the table and i am updating my predicate as the user types in the txt. (working)
Able to filter the table and the first matching row will highlighted. (working)
When the user press either "Tab" or "Enter" the highlighted row in the tableview should be set as the value in the txt.(working)
Needed:
1. When i press "Tab" or "Enter", the highlighted row will be set as the value in the text field (txt) and also the cursor should move to next focusable node. in my case it is the 2nd text field (txt1). I dont want to say txt1.requestFocus() bcoz in realtime, i have many text fields in the scene and this control will be a user control. so cant hardcode anything.
When the user types some text in the text field(not full text. eg: "do" where my table contains "Dom", "Don"), if there are multiple matches, currently both the records will be displayed in the table but the first one will be highlighted. User should be able to select the 2nd row if he wants by pressing the down arrow from the text field itself.
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
VBox root = FXMLLoader.load(this.getClass().getResource("MainView.fxml"));
Scene scene = new Scene(root,500,300);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainController.java
package application;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Popup;
public class MainController implements Initializable
{
private #FXML TableView<Person> table;
private #FXML TableColumn<Person, String> firstNameCol;
private #FXML TableColumn<Person, String> lastNameCol;
private #FXML TableColumn<Person, String> emailCol;
private #FXML TableColumn<Person, Integer> ageCol;
private #FXML TextField txt;
private #FXML TextField txt1;
private #FXML Button btn;
#Override
public void initialize(URL location, ResourceBundle resources)
{
Platform.runLater(new Runnable() {
#Override
public void run() {
txt.requestFocus();
}
});
ObservableList<Person> obsList =FXCollections.observableArrayList();
obsList.add(new Person("Sam", "P1LasttName", "P1Email#gmail.com", 20));
obsList.add(new Person("Dom", "P2LasttName", "P2Email#gmail.com", 30));
obsList.add(new Person("Ken", "P3LasttName", "P3Email#gmail.com", 40));
obsList.add(new Person("Don", "P4LasttName", "P4Email#gmail.com", 50));
obsList.add(new Person("Tom", "P5LasttName", "P5Email#gmail.com", 60));
FilteredList<Person> filteredList = new FilteredList<>(obsList, p->true);
table.setItems(filteredList);
txt.textProperty().addListener((obs, oldValue, newValue) ->{
filteredList.setPredicate(person-> {
if(newValue == null || newValue.isEmpty())
return true;
if(person.getFirstName().trim().toLowerCase().contains(newValue.toLowerCase()))
return true;
return false;
});
Platform.runLater(new Runnable() {
#Override
public void run()
{
// we don't want repeated selections
table.getSelectionModel().clearSelection();
//get the focus
table.requestFocus();
//select first item in TableView model
table.getSelectionModel().selectFirst();
//set the focus on the first element
table.getFocusModel().focus(0);
//render the selected item in the TableView
//tableClickHandler(null);
}
});
Platform.runLater(new Runnable() {
#Override
public void run()
{
txt.requestFocus();
txt.end();
}
});
});
table.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event)
{
if(event.getCode() == KeyCode.ENTER)
{
txt.setText(table.getSelectionModel().getSelectedItem().getFirstName());
}
}
});
txt.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event)
{
if(event.getCode() == KeyCode.ENTER || event.getCode() == KeyCode.TAB)
//if(event.getCode() == KeyCode.ENTER)
{
txt.setText(table.getSelectionModel().getSelectedItem().getFirstName());
/*Platform.runLater(new Runnable() {
public void run() {
txt1.requestFocus();
}
});*/
}
}
});
/*txt.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event)
{
if(event.getCode() == KeyCode.TAB)
{
//txt.setText(table.getSelectionModel().getSelectedItem().getFirstName());
if(txt.getSkin() instanceof BehaviorSkinBase)
{
//((BehaviorSkinBase)txt.getSkin()).getBehavior().traverseNext();
BehaviorBase x = ((BehaviorSkinBase)txt.getSkin()).getBehavior();
((TextFieldBehavior)x).callAction("TraverseNext");
}
event.consume();
}
}
});*/
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event)
{
/*
Popup popup = new Popup();
popup.getContent().add(new TableView());
//popup.show(txt, txt.localToScreen(0, 0).getX() + txt.getWidth()/2, txt.localToScreen(0, 0).getY() + txt.getHeight());
popup.show(txt, txt.localToScreen(0, 0).getX(), txt.localToScreen(0, 0).getY() + txt.getHeight() + 2);
*/
Parent vbox = null;
try {
vbox = FXMLLoader.load(this.getClass().getResource("TableView.fxml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Popup popup = new Popup();
popup.getContent().add(vbox);
//popup.show(txt, txt.localToScreen(0, 0).getX() + txt.getWidth()/2, txt.localToScreen(0, 0).getY() + txt.getHeight());
//popup.show(txt, txt.localToScreen(0, 0).getX(), txt.localToScreen(0, 0).getY() + txt.getHeight() + 2);
popup.show(txt, txt.localToScreen(0, 0).getX(), txt.localToScreen(0, 0).getY() + txt.getHeight() + 2);
}
});
}
}
Person.java
package application;
public class Person
{
private String firstName;
private String lastName;
private String email;
private Integer age;
public Person(){}
public Person(String firstName, String lastName, String email, Integer age)
{
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.age = age;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Integer getAge()
{
return age;
}
public void setAge(Integer age)
{
this.age = age;
}
}
application.css
.table-row-cell:selected
{
-fx-background-color: lightgreen;
/* the below style will remove the border lines of the selected row */
-fx-table-cell-border-color: transparent;
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?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.control.cell.PropertyValueFactory?>
<?import javafx.scene.layout.VBox?>
<!-- <?import application.Person?> -->
<VBox spacing="10.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainController">
<children>
<TableView fx:id="table" prefHeight="250.0" prefWidth="437.0">
<columns>
<TableColumn fx:id="firstNameCol" prefWidth="120.0" text="First Name">
<cellValueFactory><PropertyValueFactory property="firstName" /></cellValueFactory>
</TableColumn>
<TableColumn fx:id="lastNameCol" prefWidth="120.0" text="Last Name">
<cellValueFactory><PropertyValueFactory property="lastName" /></cellValueFactory>
</TableColumn>
<TableColumn fx:id="emailCol" prefWidth="120.0" text="Email">
<cellValueFactory><PropertyValueFactory property="email" /></cellValueFactory>
</TableColumn>
<TableColumn fx:id="ageCol" prefWidth="75.0" text="Age">
<cellValueFactory><PropertyValueFactory property="age" /></cellValueFactory>
</TableColumn>
</columns>
</TableView>
<Button text="Button" fx:id="btn"/>
<TextField fx:id="txt" promptText="Type to Filter" />
<TextField fx:id="txt1" promptText="Focus should be here when tab is pressed from pervious txt" />
</children>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</VBox>
TableView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.scene.layout.VBox?>
<?import application.Person?>
<?import javafx.collections.*?>
<!--
<VBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.65">
<children>
-->
<!-- <TableView xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.65" fx:id="table" prefHeight="160.0" prefWidth="440.0"> -->
<TableView xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.65" fx:id="table" prefHeight="140.0">
<columns>
<TableColumn fx:id="firstNameCol" prefWidth="120.0" text="First Name">
<cellValueFactory><PropertyValueFactory property="firstName" /></cellValueFactory>
</TableColumn>
<TableColumn fx:id="lastNameCol" prefWidth="120.0" text="Last Name">
<cellValueFactory><PropertyValueFactory property="lastName" /></cellValueFactory>
</TableColumn>
<TableColumn fx:id="emailCol" prefWidth="120.0" text="Email">
<cellValueFactory><PropertyValueFactory property="email" /></cellValueFactory>
</TableColumn>
<TableColumn fx:id="ageCol" prefWidth="75.0" text="Age">
<cellValueFactory><PropertyValueFactory property="age" /></cellValueFactory>
</TableColumn>
</columns>
<columnResizePolicy><TableView fx:constant="CONSTRAINED_RESIZE_POLICY" /></columnResizePolicy>
<items>
<FXCollections fx:factory="observableArrayList">
<Person firstName="P1FirstName" lastName="P1LasttName" email="P1Email#gmail.com" age="20"/>
<Person firstName="P2FirstName" lastName="P2LasttName" email="P2Email#gmail.com" age="30"/>
<Person firstName="P3FirstName" lastName="P3LasttName" email="P3Email#gmail.com" age="40"/>
<Person firstName="P4FirstName" lastName="P4LasttName" email="P4Email#gmail.com" age="50"/>
<Person firstName="P5FirstName" lastName="P5LasttName" email="P5Email#gmail.com" age="60"/>
</FXCollections>
</items>
</TableView>
<!--
</children>
</VBox>
-->
Any help is appreciated. Thanks!
I want to display data in tableview's column with custom rendering. I tried to adapt this tuto to my need.
Problem :
In the code example below, when I use the setCellFactory() method, the data in the corresponding column isn't displayed.
You can comment or uncomment the delimited section to see what happen in controller class.
Main class
public class CellFactory extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
AnchorPane root = FXMLLoader.load(CellFactory.class.getResource("CellFactory_Layout.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("CellFactory EXAMPLE");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Model class
public class Fruit {
private final SimpleStringProperty name;
private final SimpleIntegerProperty weight;
public Fruit(String name, int weight){
this.name = new SimpleStringProperty(name);
this.weight = new SimpleIntegerProperty(weight);
}
public String getName() {return this.name.get();}
public void setName(String v) {this.name.set(v);}
public SimpleStringProperty nameProperty() {return this.name;}
public int getWeight() {return this.weight.get();}
public void setWeight(int v) {this.weight.set(v);}
public SimpleIntegerProperty weightProperty() {return this.weight;}
}
Controller class
public class CellFactory_Controller implements Initializable {
#FXML private TableView<Fruit> fruit_tbl;
#FXML private TableColumn<Fruit, String> name_cln;
#FXML private TableColumn<Fruit, Integer> weight_cln;
// array with table data
final ObservableList<Fruit> data = FXCollections.observableArrayList();
public CellFactory_Controller() {
// some data
this.data.add(new Fruit("banana", 120));
this.data.add(new Fruit("apple", 150));
this.data.add(new Fruit("coconut", 500));
this.data.add(new Fruit("orange", 200));
}
#Override
public void initialize(URL location, ResourceBundle resources) {
this.name_cln.setCellValueFactory(new PropertyValueFactory<>("name"));
this.weight_cln.setCellValueFactory(new PropertyValueFactory<>("weight"));
this.weight_cln.setCellValueFactory(cellData -> cellData.getValue().weightProperty().asObject());
// comment or uncomment to see what happen
///////////////////////////////////////////////////////////////////////
this.weight_cln.setCellFactory(column -> new TableCell<Fruit, Integer>() {
#Override
protected void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setStyle("");
} else {
if (item < 10) {
setTextFill(Color.CHOCOLATE);
} else {
setTextFill(Color.BLACK);
setStyle("");
}
}
}
});
///////////////////////////////////////////////////////////////////////
this.fruit_tbl.setItems(this.data);
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="CellFactory.CellFactory_Controller">
<children>
<TableView fx:id="fruit_tbl" layoutX="189.0" layoutY="93.0" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="name_cln" prefWidth="471.0" text="FRUIT" />
<TableColumn fx:id="weight_cln" prefWidth="75.0" text="WEIGHT" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
</children>
</AnchorPane>
Question :
From my code example, how can I use custom cell renderer properly (with int data type) to display my data ?
you forgot to add the following statement:
setText(String.valueOf(item));
So, your setCellFactory() method should look like the following:
this.weight_cln.setCellFactory(column -> new TableCell<Fruit, Integer>() {
#Override
protected void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setStyle("");
} else {
setText(String.valueOf(item));
if (item < 200) {
setTextFill(Color.CHOCOLATE);
} else {
setTextFill(Color.BLACK);
}
}
}
});
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);
}
}
I'm a JavaFX newbie and, for some reason, my data doesn't show up in the tableview.
Controller Class:
public class TxstController implements Initializable {
#FXML private Label label;
#FXML private TextField searchBar;
#FXML private Button searchButton;
#FXML private ListView dateList;
#FXML private TableView<Service> serviceTable;
#FXML private TableColumn<Service, Integer> qntColumn;
#FXML private TableColumn<Service, String> descColumn;
#FXML private TableColumn<Service, Double> priceColumn;
#FXML
private void handleSearchButton(ActionEvent event) {
//do stuff when searchButton get clicked
List<String> lista = new ArrayList<>();
lista.add("Queijo");
lista.add("Azeitonas");
lista.add("Cebola");
fillListWith(lista);
}
#FXML
private void textFieldKeyHandler(KeyEvent event){
if(event.getCode() == KeyCode.ENTER){
//do stuff when in text field you click enter
}
}
private void fillListWith(List<String> list){
//adds string list at param to dateList
dateList.setItems(FXCollections.observableList(list));
}
#Override
public void initialize(URL url, ResourceBundle rb) {
qntColumn.setCellValueFactory(new PropertyValueFactory<>("qnt"));
descColumn.setCellValueFactory(new PropertyValueFactory<>("desc"));
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
ObservableList<Service> lista = FXCollections.observableArrayList();
lista.add(new Service(3,"Queijo com ",19.30));
lista.add(new Service(2,"asdasasd",5.21));
lista.add(new Service(3,"Queijo com ",19.30));
lista.add(new Service(3,"Queijo com ",19.30));
lista.add(new Service(3,"Queijo com ",19.30));
lista.add(new Service(3,"Queijo com ",19.30));
serviceTable.setItems(lista);
}
Service class:
class Service {
private int qnt;
private String desc;
private double price;
public Service(int qnt,String desc, double price){
this.qnt = qnt;
this.desc = desc;
this.price = price;
}
public int getqnt(){
return this.qnt;
}
public String getdesc(){
return this.desc;
}
public double getprice(){
return this.price;
}
public void setqnt(int qnt){
this.qnt = qnt;
}
public void setdesc(String desc){
this.desc = desc;
}
public void setprice(double price){
this.price = price;
}
FXML File:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="758.0" prefWidth="848.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="elteste.TxstController">
<children>
<TextField fx:id="searchBar" layoutX="110.0" layoutY="124.0" onKeyPressed="#textFieldKeyHandler" prefHeight="26.0" prefWidth="487.0" />
<Button fx:id="searchButton" layoutX="608.0" layoutY="124.0" mnemonicParsing="false" onAction="#handleSearchButton" prefHeight="26.0" prefWidth="84.0" text="Pesquisar" />
<ListView fx:id="dateList" layoutX="18.0" layoutY="158.0" onMouseClicked="#listMouseSelectHandler" prefHeight="575.0" prefWidth="175.0" />
<Label layoutX="30.0" layoutY="128.0" prefHeight="16.0" prefWidth="69.0" text="Matricula:" textAlignment="CENTER" />
<Button layoutX="702.0" layoutY="124.0" mnemonicParsing="false" text="Adicionar Servico" />
<Label fx:id="label" layoutX="369.0" layoutY="54.0" prefHeight="37.0" prefWidth="207.0" text="Label" />
<TableView fx:id="serviceTable" layoutX="207.0" layoutY="158.0" prefHeight="575.0" prefWidth="603.0">
<columns>
<TableColumn fx:id="qntColumn" prefWidth="113.0" text="Quantidade" />
<TableColumn fx:id="descColumn" prefWidth="362.0" text="Descricão" />
<TableColumn fx:id="priceColumn" minWidth="0.0" prefWidth="127.0" text="Preco" />
</columns>
</TableView>
</children>
</AnchorPane>
There are no erros, and when the table pops up, i can select the rows, that are filled, for example, if the list has 3 objects, i can select 3 rows, the others i cant, but, for some reason, the content doesnt show up.
You named the getters and setters wrong in Service.
Name them according to the camelCase naming convention:
public void setQnt(int qnt){
this.qnt = qnt;
}