Why my TableView not getting refreshed or auto updated? - javafx

I tried a lot but my value entered in the textfield is not getting populated to tableview when add button is clicked.Please give me a solution to populate values into the tableview whenever i click on add button !
public class Refreshtable extends Application {
#FXML
private TextField fname;
private final TableView<Person> table = new TableView<>();
private final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("Jacob"));
final HBox hb = new HBox();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primarystage) {
Scene scene = new Scene(new Group());
// this.primaryStage.setTitle("Table View Sample");
primarystage.setWidth(450);
primarystage.setHeight(550);
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
table.setEditable(true);
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory("firstName"));
table.setItems(data);
table.getColumns().addAll(firstNameCol);
final Button addButton = new Button("Add");
addButton.setOnAction((ActionEvent e) -> {
System.out.println("u entered");
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Refreshtable.class.getResource("newaddframe.fxml"));
AnchorPane anchorpane = (AnchorPane) loader.load();
Stage dialogStage = new Stage();
dialogStage.setTitle("Main");
dialogStage.initModality(Modality.WINDOW_MODAL);
Scene scenee = new Scene(anchorpane);
dialogStage.setScene(scenee);
dialogStage.showAndWait();
} catch (IOException es) {
es.printStackTrace();}
});
hb.getChildren().addAll(addButton);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll( table, hb);
((Group) scene.getRoot()).getChildren().addAll(vbox);
primarystage.setScene(scene);
primarystage.show();
}
#FXML
private void addd(){
data.add(new Person(
fname.getText()));
fname.clear();
}
public static class Person {
private final SimpleStringProperty firstName;
private Person(String fName) {
this.firstName = new SimpleStringProperty(fName);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
}
}

I will not talk about the (many) issues with your code and keep the answer short, addressing your original problem.
You need to add the data entered by the user to the ObservableList backing the TableView.
#FXML
private void update()
{
...
// Create new instance of UserData
UserData userData = new UserData(name.getText(), country.getText());
// Add it to the backing list
data.add(userData);
}

Sample refresh tableview code:
Cloud.java
public class Cloud extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
/**
* The data as an observable list of Persons.
*/
private ObservableList<Person> personData = FXCollections.observableArrayList();
/**
* Constructor
*/
public Cloud() {
}
/**
* Returns the data as an observable list of Persons.
* #return
*/
public ObservableList<Person> getPersonData() {
return personData;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
// Set the application icon.
this.primaryStage.getIcons().add(new Image("file:resources/images/address_book_32.png"));
showPersonOverview();
}
/**
* Initializes the root layout and tries to load the last opened
* person file.
*/
/**
* Shows the person overview inside the root layout.
*/
public void showPersonOverview() {
try {
// Load person overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Cloud.class.getResource("root.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
Stage dialogStagee = new Stage();
dialogStagee.setTitle("Edit Person");
dialogStagee.initModality(Modality.WINDOW_MODAL);
dialogStagee.initOwner(primaryStage);
Scene scene = new Scene(personOverview);
dialogStagee.setScene(scene);
// Give the controller access to the main app.
rootcontroller controller = loader.getController();
controller.setMainApp(this);
dialogStagee.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Opens a dialog to edit details for the specified person. If the user
* clicks OK, the changes are saved into the provided person object and true
* is returned.
*
* #param person the person object to be edited
* #return true if the user clicked OK, false otherwise.
*/
public boolean showPersonEditDialog(Person person) {
try {
// Load the fxml file and create a new stage for the popup dialog.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Cloud.class.getResource("add.fxml"));
AnchorPane page = (AnchorPane) loader.load();
// Create the dialog Stage.
Stage dialogStage = new Stage();
dialogStage.setTitle("Edit Person");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
// Set the person into the controller.
addcontroller controller = loader.getController();
controller.setDialogStage(dialogStage);
controller.setPerson(person);
// Set the dialog icon.
dialogStage.getIcons().add(new Image("file:resources/images/edit.png"));
// Show the dialog and wait until the user closes it
dialogStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
Person.java
public class Person {
private final StringProperty firstName;
private final StringProperty lastName;
/**
* Default constructor.
*/
public Person() {
this(null, null);
}
/**
* Constructor with some initial data.
*
* #param firstName
* #param lastName
*/
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
}
addcontroller.java
public class addcontroller {
#FXML
private TextField firstNameField;
#FXML
private TextField lastNameField;
private Stage dialogStage;
private Person person;
// private boolean okClicked = false;
public void setDialogStage(Stage dialogStage) {
this.dialogStage = dialogStage;
}
/**
* Sets the person to be edited in the dialog.
*
* #param person
*/
public void setPerson(Person person) {
this.person = person;}
#FXML
private void handleOk() {
person.setFirstName(firstNameField.getText());
person.setLastName(lastNameField.getText());
dialogStage.close();
}
}
rootcontroller.java
public class rootcontroller {
#FXML
private TableView<Person> personTable;
#FXML
private TableColumn<Person, String> firstNameColumn;
#FXML
private TableColumn<Person, String> lastNameColumn;
// Reference to the main application.
private Cloud mainApp;
/**
* The constructor.
* The constructor is called before the initialize() method.
*/
public rootcontroller() {
}
#FXML
private void initialize() {
// Initialize the person table with the two columns.
firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
}
public void setMainApp(Cloud mainApp) {
this.mainApp = mainApp;
personTable.setItems(mainApp.getPersonData());
}
#FXML
private void handleNewPerson() {
Person tempPerson = new Person();
System.out.println("1");
mainApp.showPersonEditDialog(tempPerson);
mainApp.getPersonData().add(tempPerson);
}
}
root.fxml
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cloud.rootcontroller">
<children>
<TableView fx:id="personTable" layoutX="215.0" layoutY="106.0" prefHeight="200.0" prefWidth="200.0">
<columns>
<TableColumn fx:id="firstNameColumn" prefWidth="75.0" text="name" />
<TableColumn fx:id="lastNameColumn" prefWidth="75.0" text="country" />
</columns>
</TableView>
<Button layoutX="415.0" layoutY="334.0" mnemonicParsing="false" onAction="#handleNewPerson" text="add" />
</children>
</AnchorPane>
add.fxml
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cloud.addcontroller">
<children>
<TextField fx:id="firstNameField" layoutX="97.0" layoutY="113.0" />
<TextField fx:id="lastNameField" layoutX="259.0" layoutY="113.0" />
<Button layoutX="451.0" layoutY="113.0" mnemonicParsing="false" onAction="#handleOk" text="save" />
</children>
</AnchorPane>

Related

How to add a javafx shortcut key combinations for buttons

My UI has a adding button and I want to assign a keyboard shortcut combination for that. I have failed to use the setAcceleartor for this purpose.
What is the easiest way to set up keyboard shortcuts in javafx applications?
button declaration in the UI:
<Button fx:id="addButton" alignment="CENTER" minWidth="-Infinity" mnemonicParsing="false" onAction="#addAction" prefHeight="31.0" prefWidth="130.0" text="Add" HBox.hgrow="ALWAYS" />
Controller button binding:
#FXML
private Button addButton;
The method that wants to setOnAction for the shortcut for the button:
public void addAction(ActionEvent event) throws SQLException, ClassNotFoundException {
if (validateInput()) {
String productName = productField.getText();
double unitPrice = Double.parseDouble(priceField.getText());
int quantity = Integer.parseInt(quantityField.getText());
double total = unitPrice * quantity;
ITEMLIST.add(new Item(productName, unitPrice, quantity, total));
calculation();
resetAdd();
productTableView.getSelectionModel().clearSelection();
ObservableList<Product> productsData = ProductDAO.searchProducts();
populateProducts(productsData);
searchField.setText("");
}
}
initialize() method:
#FXML
private void initialize() throws SQLException, ClassNotFoundException, IOException {
setSaveAccelerator(addButton);
}
The code I tried with setAccelerator:
private void setSaveAccelerator(final Button button) {
Scene scene = button.getScene();
if (scene == null) {
throw new IllegalArgumentException("setSaveAccelerator must be called when a button is attached to a scene");
}
scene.getAccelerators().put(
new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN),
new Runnable() {
#FXML public void run() {
button.fire();
}
}
);
}
In your setSaveAccelerator method, instead of directly calling addAction(ActionEvent event), just instruct the button to fire its event to its listeners such as: button.fire(). For example:
private void setSaveAccelerator(Button button) {
if(button==null) {
System.out.println("Button is null! "); // check that the button was injected properly through your fxml
}
Scene scene = button.getScene();
if (scene == null) {
throw new IllegalArgumentException("setSaveAccelerator must be called when a button is attached to a scene");
}
scene.getAccelerators().put(
new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN),
new Runnable() {
#FXML public void run() {
button.fire();
}
}
);
}
EDIT
To also avoid the IllegalArgumentException you must attach the accelerator after the button is attached to a scene. I managed to achieve this by creating a public method in the controller to attach the accelerator after the scene has been set. Then, in the class where the scene is loaded the controller's method can be called which sets up this functionality. See the example below:
In the controller class (in my case MainController):
public void setup() {
setSaveAccelerator(button);
}
In your main class when loading the fxml file:
FXMLLoader loader = new FXMLLoader(MainController.class.getResource("mainFXML.fxml"));
AnchorPane page = (AnchorPane) loader.load();
MainController controller = loader.getController();
Scene scene = new Scene(page);
controller.setup(); // calls the setup method attaching the accelerators
FULL EXAMPLE
Main class:
public class Main extends Application{
public static Stage primaryStage;
#Override
public void start(Stage primaryStage) throws Exception {
Main.primaryStage=primaryStage;
FXMLLoader loader = new FXMLLoader(MainController.class.getResource("mainFXML.fxml"));
AnchorPane page = (AnchorPane) loader.load();
MainController controller = loader.getController();
Scene scene = new Scene(page);
primaryStage.setTitle("Shortcut example");
primaryStage.setScene(scene);
controller.setup();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Maincontroller:
public class MainController {
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private Button button;
#FXML
private AnchorPane rootPane;
#FXML
private TextArea textarea;
#FXML
void action(ActionEvent event) {
textarea.setText("Action fired!!");
}
#FXML
void initialize() {
assert button != null : "fx:id=\"button\" was not injected: check your FXML file 'MainFXML.fxml'.";
assert rootPane != null : "fx:id=\"rootPane\" was not injected: check your FXML file 'MainFXML.fxml'.";
assert textarea != null : "fx:id=\"textarea\" was not injected: check your FXML file 'MainFXML.fxml'.";
}
public void setup() {
setSaveAccelerator(button);
}
private void setSaveAccelerator(Button button) {
if(button==null) {
System.out.println("Button null!!");
}
Scene scene = button.getScene();
if (scene == null) {
throw new IllegalArgumentException("setSaveAccelerator must be called when a button is attached to a scene");
}
scene.getAccelerators().put(
new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN),
new Runnable() {
#FXML public void run() {
button.fire();
}
}
);
}
}
MainFXML.fxml
<AnchorPane fx:id="rootPane" prefHeight="408.0" prefWidth="330.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainController">
<children>
<Button fx:id="button" layoutX="139.0" layoutY="350.0" mnemonicParsing="false" onAction="#action" text="Button" />
<TextArea fx:id="textarea" layoutX="73.0" layoutY="38.0" prefHeight="200.0" prefWidth="200.0" />
</children>
</AnchorPane>

How to change values in tableview simultaneously whenever i select an corresponding item from comboboxtablecell

I tried but I got stuck at a point where am getting the corresponding values of the selected item from comboboxtablecell but cannot add the values to the corresponding column in the table view
Controller.java
public class controller {
GetConnection gc = new GetConnection();
PreparedStatement pst;
ResultSet rs;
Statement st;
private ObservableList<Users> datas = FXCollections.observableArrayList();
public controller(){}
#FXML
private TableView<Users> table;
#FXML
private TableColumn<Users,String> c1;
#FXML
private TableColumn<Users,String> c2;
#FXML
private TableColumn<Users,String> c3;
#FXML
private void editable() {
try {
ObservableList<Users> datas = FXCollections.observableArrayList();
ObservableList<String> item = FXCollections.observableArrayList();
ObservableList<String> iprice = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
String cat=rs.getString("unitprice");
item.add(name);
iprice.add(cat);
System.out.println("probs" + item);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode"),rs2.getString("category"),rs2.getString("unitprice")));
}
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(item));
for(String name:item){
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(item));
System.out.println("hell3"+name);
}c1.setOnEditCommit( ( TableColumn.CellEditEvent<Users, String> e ) ->
{
String newValue = e.getNewValue();
int index = e.getTablePosition().getRow();
System.out.println("position"+index);
try{
System.out.println("new values"+newValue);
String dsql="SELECT category,unitprice FROM itemsadd WHERE itemcode=?;";
pst=gc.getConnection().prepareStatement(dsql);
pst.setString(1, newValue); //this replaces the 1st "?" in the query for username
rs=pst.executeQuery();
while(rs.next())
{
String category1 = rs.getString(1);
String price1 = rs.getString(2);
System.out.println("category is"+category1);
System.out.println("unitprice is"+price1);
}
}catch(Exception ed){} } );
c2.setCellValueFactory(new PropertyValueFactory("category"));
c2.setCellFactory(TextFieldTableCell.forTableColumn());
c3.setCellValueFactory(new PropertyValueFactory("unitprice"));
c3.setCellFactory(ComboBoxTableCell.forTableColumn(iprice));
table.setEditable(true);
table.getItems().clear();
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class Users {
private StringProperty Itemc;
private StringProperty category;
private StringProperty unitprice;
private Users(String Itemc,String category,String unitprice) {
this.Itemc= new SimpleStringProperty(Itemc);
this.category=new SimpleStringProperty(category);
this.unitprice=new SimpleStringProperty(unitprice);
}
public String getItemc() {
return Itemc.get();
}
public void setItemc(String Itemc) {
this.Itemc.set(Itemc);
}
public StringProperty ItemcProperty() {
return Itemc;
}
public String getcategory() {
return category.get();
}
public void setcategory(String category) {
this.category.set(category);
}
public StringProperty categoryProperty() {
return category;
}
public String getunitprice() {
return unitprice.get();
}
public void setunitprice(String unitprice) {
this.unitprice.set(unitprice);
}
public StringProperty unitpriceProperty() {
return unitprice;
}}
}
Table.fxml
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication47.controller">
<children>
<TableView fx:id="table" editable="true" layoutX="136.0" layoutY="58.0" onKeyPressed="#editable" prefHeight="200.0" prefWidth="335.0">
<columns>
<TableColumn fx:id="c1" prefWidth="116.0" text="Code" />
<TableColumn fx:id="c2" prefWidth="115.0" text="Address" />
<TableColumn fx:id="c3" prefWidth="102.0" text="Price" />
</columns>
</TableView>
</children>
</AnchorPane>
Tableview.java
public class Tableveiw extends Application {
private Stage primaryStage;
private AnchorPane pane;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
showPerson();
}
public void showPerson() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Tableveiw.class
.getResource("table.fxml"));
pane= (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}}
public static void main(String[] args) {
launch(args);
}
}
GetConnection.java
public class GetConnection{
public Connection getConnection() throws Exception
{
Connection con=null;
try {
System.out.println("MySQL Connect Example.");
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+dbName,"root","");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String arg[])
{
GetConnection con =new GetConnection();
System.out.println("Connection"+con);
}
}
The above code is runnable and simplified and the program has a tableview and three column with first columncell is a comboboxtablecell having items in it.The second columncell is a editable text field and third column cell is a comboboxtablecell with its items in database.I have tried myself where am getting values of the corresponding values in the row whenever I select value in combo box table cell in category.java System.out.println("categoryis"+category1);
System.out.println("unitprice is"+price1); .Please help me to change values in tableview whenever I select item in the combobox in table view.
You need to
Go to your cell factory code
1add event handler for combobox selection change
Get current row
Get current item
Change the value you need
Sample ComboBox Selected items changing values of tableview example.
Tablecombo.java
public class Tablecombo extends Application {
Stage primaryStage;
Scene scene;
String username;
AnchorPane anchorpane;
BorderPane borderpane;
// Pane pane;
BorderPane border;
Stage sstage;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Login");
root();
}
public void root() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Tablecombo.class.getResource("tcombo.fxml"));
anchorpane = (AnchorPane) loader.load();
Stage dialogStage = new Stage();
dialogStage.setTitle("Main");
dialogStage.initModality(Modality.WINDOW_MODAL);
Scene scene = new Scene(anchorpane);
dialogStage.setScene(scene);
dialogStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
tablecontroller.java
public class tablecontroller {
Tablecombo main;
GetConnection gc = new GetConnection();
PreparedStatement pst;
ResultSet rs;
public tablecontroller(){
}
#FXML
private TableView<UserData> table4;
#FXML
private TableColumn<UserData,String> c1;
#FXML
private TableColumn<UserData,String> c2;
#FXML
private void editable() {
try {
ObservableList<UserData> datas = FXCollections.observableArrayList();
ObservableList<String> names = FXCollections.observableArrayList();
ObservableList<String> rat = FXCollections.observableArrayList();
// ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from pdfs";
// String msql="select * from category";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
String cat=rs.getString("country");
rat.add(cat);
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement().executeQuery("SELECT * FROM pdfs LIMIT 1");
//ObservableList<Users> datas = FXCollections.observableArrayList();
while (rs2.next()) {
datas.add(new UserData(rs2.getString("name"),rs2.getString("country")));
}
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(names));
for(String name:names){
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
// System.out.println("hell2"+name);
c1.setCellFactory(ComboBoxTableCell.forTableColumn(names));
System.out.println("hell3"+name);
}
c1.setOnEditCommit( ( TableColumn.CellEditEvent<UserData, String> e ) ->
{
String newValue = e.getNewValue();
int index = e.getTablePosition().getRow();
System.out.println("position"+index);
try{
ObservableList<UserData> data = FXCollections.observableArrayList();
System.out.println("new values"+newValue);
String dsql="SELECT * FROM pdfs WHERE name=?;";
pst=gc.getConnection().prepareStatement(dsql);
System.out.println("quer"+dsql);
pst.setString(1, newValue); //this replaces the 1st "?" in the query for username
rs=pst.executeQuery();
while(rs.next())
{
data.add(new UserData(rs.getString("name"),rs.getString("country")));
}
table4.setItems(data);
String a = rs.getString(1);
String b = rs.getString(2);
String c = rs.getString(3);
System.out.println("su"+a);
System.out.println("ma"+b);
System.out.println("man"+c);
}catch(Exception ed){} } );
c2.setCellValueFactory(new PropertyValueFactory("quantity"));
c2.setCellFactory(TextFieldTableCell.forTableColumn());
table4.setEditable(true);
table4.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
}
UserData.java
public class UserData {
private StringProperty Itemc;
private StringProperty quantity;
public UserData(String Itemc,String quantity) {
//this.Quantity = new SimpleStringProperty(Quantity);
this.Itemc= new SimpleStringProperty(Itemc);
this.quantity = new SimpleStringProperty(quantity);
}
public String getItemc() {
return Itemc.get();
}
public void setItemc(String Itemc) {
this.Itemc.set(Itemc);
}
public StringProperty ItemcProperty() {
return Itemc;
}
public void setquantity(String quantity) {
this.quantity.set(quantity);
}
public String getquantity() {
return quantity.get();
}
public StringProperty quantityProperty() {
return quantity;
}
}
tcombo.fxml
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="tablecombo.tablecontroller">
<children>
<TableView fx:id="table4" layoutX="168.0" layoutY="81.0" onKeyPressed="#editable" prefHeight="200.0" prefWidth="230.0">
<columns>
<TableColumn fx:id="c1" prefWidth="75.0" text="name" />
<TableColumn fx:id="c2" prefWidth="75.0" text="country" />
</columns>
</TableView>
</children>
</AnchorPane>

Java FXML Add ObservableList to TableView

I can't display my Observable List in the table view. I don't get any error. I was check if Observable List and List have value and everything looks fine. I don't have any idea where is a problem. I was try to add ValueFactory also in FXML code and it still don't work
FXML
<TableView fx:id="laczenie" layoutX="641.0" layoutY="52.0" prefHeight="415.0" prefWidth="438.0">
<columns>
<TableColumn prefWidth="75.0" text="Wezly" fx:id="C1" >
</TableColumn>
<TableColumn prefWidth="361.0" text="MozliwePolaczenia" fx:id="C2">
</TableColumn>
</columns>
</TableView>
JavaFx Controller
public class FXMLDocumentController implements Initializable {
private JavaFXApplication4 mainApp;
public List<Krawendzie> list = new ArrayList<Krawendzie>();
#FXML
private TableColumn C1;
#FXML
private TableColumn C2;
#FXML
private TableView<Krawendzie> laczenie;
#FXML
private Label label;
#FXML
private ComboBox<String> combo;
#FXML
private GridPane Scena;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
C1.setCellValueFactory(new PropertyValueFactory<Krawendzie,Integer>("Wezel"));
C2.setCellValueFactory(new PropertyValueFactory<Krawendzie,Integer>("Mozliwosci"));
combo.getItems().addAll("2","3","4","5","6","7","8");
list.removeAll(list);
}
#FXML
private void itemselected(ActionEvent event){
}
#FXML
private void rysuj(ActionEvent event) {
rysuj2(Integer.parseInt(combo.getValue()));
}
private void rysuj2(Integer Ilosc){
list.removeAll(list);
Scena.getChildren().clear();
laczenie = new TableView<Krawendzie>();
File f = new File("././Image/Imapges1.jpg");
Image image = new Image(f.toURI().toString());
Integer ilosc = 0;
for (int i = 0; i<=Ilosc;i++)
{
for(int k = 1;k<Scena.getColumnConstraints().size();k=k+2)
{
if(k%2 != 0)
{
Circle circle = new Circle(20, 20, 20);
circle.setFill(new ImagePattern(image));
Scena.add(circle,k,i);
list.add(new Krawendzie(ilosc,ilosc));
ilosc++;
}
if(ilosc == Ilosc)
break;
}
if(ilosc == Ilosc)
break;
}
getData();
}
public void getData()
{
ObservableList<Krawendzie> obsList = FXCollections.observableArrayList(list);
laczenie.setItems(obsList);
//return obsList;
}
}
And Main Application
public class JavaFXApplication4 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);
}
}
sorry for question i have an answer. I only need to delete
laczenie = new TableView();
because i was create a new object of talbeview so i can't work

javaFX - how to use function or object of a controller from another controller

I have seen a lot of question similar to mine, but I didn't figure it out how to solve my problem, so there is my code:
I have a simple main:
MainClassFXGui.java
public class MainClassFXGui extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MyProgramMainGuiTab.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Assicurazione");
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
and three fxml files, one of them that contains the other two, by the tag
<fx:include source="MyTab1.fxml" />
MyProgramMainGuiTab.fxml
...
<TabPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="5000.0" prefWidth="5000.0" tabClosingPolicy="UNAVAILABLE">
<tabs>
<Tab closable="false" text="MyTab1">
<content>
<fx:include source="MyTab1.fxml" />
</content>
</Tab>
<Tab closable="false" text="MyTab2">
<content>
<fx:include source="MyTab2.fxml" />
</content>
</Tab>
</tabs>
</TabPane>
...
and three controller:
MyProgramMainGuiTabController.java
....
#FXML
private Label LeftSt;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
LeftSt.setText("");
}
public void setLeftSt(String st){
LeftSt.setText(st);
}
...
MyTab1Controller.java
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
setLeftSt("Can I change the label of the MyProgramMainGuiTabController?");
}
I tried in this way:
MyTab1Controller.java
private MyProgramMainGuiTabController controller;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
controller.setLeftSt("Can I change the label of the MyProgramMainGuiTabController?");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
FXMLLoader fxmlLoader = new
FXMLLoader(getClass().getResource("MyProgramMainGuiTab.fxml"));
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
controller = (MyProgramMainGuiTabController)fxmlLoader.getController();
}
But I have a null pointer exception or if I move the code for the instanzialization of the object 'controller' in the handleButtonAction function, I don't have any error, but the label does not change.
Maybe I can create a static Scene and a static Stage in the MainClassFXGui.java?
but then I don't know how I could use them...
MainClassFXGui.java
public class MainClassFXGui extends Application {
static private Scene scene;
static private Stage stage;
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MyProgramMainGuiTab.fxml"));
this.scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Assicurazione");
stage.show();
this.stage = stage;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public static Scene getScene(){
return AssicurazioneFXGui.scene;
}
public static Stage getStage(){
return AssicurazioneFXGui.stage;
}
}
can I do something with getScene() or getStage()? any idea or suggest?
thanks to everyone
Define a StringProperty in MyTab1Controller, with the usual methods:
public class MyTab1Controller {
private final StringProperty leftSt = new SimpleStringProperty();
public StringProperty leftStProperty() {
return leftSt ;
}
public final String getLeftSt() {
return leftStProperty().get();
}
public final void setLeftSt(String leftSt) {
leftStProperty().set(leftSt);
}
// ...
#FXML
public void handleButtonAction() {
setLeftSt(...);
}
// ...
}
Now assign an fx:id attribute to the fx:include tag:
<Tab closable="false" text="MyTab1">
<content>
<fx:include fx:id="myTab1" source="MyTab1.fxml" />
</content>
</Tab>
This means you can inject the controller for MyTab1.fxml into the controller for the FXML where it is included (MyProgramMainGuiTabController):
public class MyProgramMainGuiTabController {
#FXML
private MyTab1Controller myTab1Controller ;
}
and then you can just observe the property and update the label when it changes:
public class MyProgramMainGuiTabController {
#FXML
private MyTab1Controller myTab1Controller ;
#FXML
private Label leftSt;
public void initialize() {
leftSt.setText("");
myTab1Controller.leftStProperty().addListener((obs, oldValue, newValue) ->
leftSt.setText(newValue));
}
}
Note the rule here is that the field name for the controller is the value of the fx:id attribute with the word "Controller" appended: myTab1 in the fx:id resolves to myTab1Controller for the field where the controller is injected. See NestedControllers for more information.
At the moment I have solved in this way. If anyway someone has a better solution, please write. Also because this does not solve the problem if I need to execute a function.. thanks
MyProgramMainGuiTabController.fxml
...
#FXML
private Label LeftSt;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
LeftSt.setText("");
}
...
MyTab1Controller.fxml
#FXML
private Button myObject;
private Scene scene;
private Label lblDataLeft;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
setLeftSt("this works!");
}
public void setLeftSt(String st){
if(this.scene == null)
this.scene = myObject.getScene();
if(this.lblDataLeft==null)
this.lblDataLeft = (Label) scene.lookup("#LeftSt");
if (this.lblDataLeft!=null)
this.lblDataLeft.setText(st);
}

Why isn't the TableView getting populated?

I'm trying to build an audio library using javafx and scene builder.
This is my relevant bit from my fxml file:
TableView fx:id="tableView" layoutX="45.0" layoutY="85.0" prefHeight="481.0" prefWidth="573.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn prefWidth="154.0" text="Album" />
<TableColumn prefWidth="160.0" text="Songs" />
<TableColumn prefWidth="133.0" text="Artist" />
<TableColumn prefWidth="125.0" text="Genre" />
</columns>
</TableView>
It is linked with my controller class.
This is the data I am trying to populate it with from my Controller class:
final ObservableList<Integer> ratingSample = FXCollections.observableArrayList(1, 2, 3, 4, 5);
ObservableList<String> artists = FXCollections.observableArrayList("Adele",
"Unknown", "Beyonce", "Rihanna", "Avril", "Disturbia", "Kid Rock", "Jessi J", "Unknown", "Unknown");
final ObservableList<Integer> ratingSample = FXCollections.observableArrayList(1, 2, 3, 4, 5);
ObservableList<String> artists = FXCollections.observableArrayList("Adele",
"Unknown", "Beyonce", "Rihanna", "Avril", "Disturbia", "Kid Rock", "Jessi J", "Unknown", "Unknown");
ObservableList<String> titles = FXCollections.observableArrayList("Running in the Deep",
"Title 01","Title 09","What's my name","What the Hell","Disturbia","Kid Rock","Price Tag","Title 2","09");
#FXML
TableView<Music> table = new TableView<>();
#FXML
private TableView<Music> tblViewer = new TableView<Music>();
#FXML
TableColumn<Music, Album> albumArt = new TableColumn<Music, Album>("Album Art");
#FXML
TableColumn<Music, String> title = new TableColumn<Music, String>("Title");
#FXML
TableColumn<Music, String> artist = new TableColumn<Music, String>("Artist");
#FXML
TableColumn<Music, Integer> rating = new TableColumn<Music, Integer>("Rating");
#FXML
public TableView getTableView() {
albumArt.setCellValueFactory(new PropertyValueFactory("album"));
title.setCellValueFactory(new PropertyValueFactory("title"));
artist.setCellValueFactory(new PropertyValueFactory("artist"));
rating.setCellValueFactory(new PropertyValueFactory("rating"));
// SETTING THE CELL FACTORY FOR THE ALBUM ART
albumArt.setCellFactory(new Callback<TableColumn<Music, Album>, TableCell<Music, Album>>() {
#Override
public TableCell<Music, Album> call(TableColumn<Music, Album> param) {
TableCell<Music, Album> cell = new TableCell<Music, Album>() {
#Override
public void updateItem(Album item, boolean empty) {
if (item != null) {
HBox box = new HBox();
box.setSpacing(10);
VBox vbox = new VBox();
vbox.getChildren().add(new Label(item.getArtist()));
vbox.getChildren().add(new Label(item.getAlbum()));
ImageView imageview = new ImageView();
imageview.setFitHeight(50);
imageview.setFitWidth(50);
imageview.setImage(new Image(MusicTable.class.getResource("img").toString() + "/" + item.getFilename()));
box.getChildren().addAll(imageview, vbox);
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(box);
}
}
};
System.out.println(cell.getIndex());
return cell;
}
});
// SETTING THE CELL FACTORY FOR THE RATINGS COLUMN
rating.setCellFactory(new Callback<TableColumn<Music, Integer>, TableCell<Music, Integer>>() {
#Override
public TableCell<Music, Integer> call(TableColumn<Music, Integer> param) {
TableCell<Music, Integer> cell = new TableCell<Music, Integer>() {
#Override
public void updateItem(Integer item, boolean empty) {
if (item != null) {
ChoiceBox choice = new ChoiceBox(ratingSample);
choice.getSelectionModel().select(ratingSample.indexOf(item));
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(choice);
}
}
};
return cell;
}
});
//ADDING ALL THE COLUMNS TO TABLEVIEW
table.getColumns().addAll(albumArt, title, artist, rating);
//ADDING ROWS INTO TABLEVIEW
ObservableList<Music> musics = FXCollections.observableArrayList();
for (int i = 0; i < 10; i++) {
Album al = new Album(i + 1 + ".jpg", artists.get(i), artists.get(i));
Music m = new Music(artists.get(i),al,titles.get(i),i%5);
musics.add(m);
}
table.setItems(musics);
return table;
}
Music class:
package sample;
import javafx.beans.property.*;
public class Music {
//Properties
private SimpleStringProperty artist = new SimpleStringProperty();
private ObjectProperty albumArt= new SimpleObjectProperty();
private StringProperty title= new SimpleStringProperty();
public Music(String artist, Album album, String title, int year) {
setArtist(artist);
setAlbum(album);
setTitle(title);
/*setGenre (genre);
setYear(year);
setRating(rating);*/
}
//ARTIST -----------
public void setArtist(String art){
artist.set(art);
}
public String getArtist(){
return artist.get();
}
public StringProperty artistProperty(){
return artist;
}
//ALBUM ------------
public void setAlbum(Album alb){
albumArt.set(alb);
}
public Object getAlbum(){
return albumArt.get();
}
public ObjectProperty albumProperty(){
return albumArt;
}
//TITLE -------------
public void setTitle(String tit){
title.set(tit);
}
public String getTitle(){
return title.get();
}
public StringProperty titleProperty(){
return title;
}
/*//GENRE --------------
public void setGenre(String gen){
genre.set(gen);
}
public String setGenre(){
return genre.get();
}
public StringProperty genreProperty(){
return genre;
}
//YEAR --------------
public void setYear(int yea){
year.set(yea);
}
public Integer getYear(){
return year.get();
}
public IntegerProperty yearProperty(){
return year;
}
//RATING --------------
public void setRating(int rat){
rating.set(rat);
}
public Integer getRating(){
return rating.get();
}
public IntegerProperty ratingProperty(){
return rating;
}
*/
}
So, the code runs, but no data is shown on the table.
I have tried quite a few versions of this. However nothing seems to work. Could somebody help me understand what I am doing wrong?

Resources