I want to load some data from a database into my tableview.I've got a code and it works fine but no my tableview is empty ....
Here is my fxml file:
<TableView fx:id="libraryNode" editable="true" onKeyPressed="#onLibraryRequest" xmlns:fx="http://javafx.com/fxml" fx:controller="mediabox.app.controller.MusicscreenController">
<columns>
<TableColumn text="Index" prefWidth="40" >
<cellValueFactory>
<PropertyValueFactory property="id" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Titel" prefWidth="150">
<cellValueFactory>
<PropertyValueFactory property="titel" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Dauer" prefWidth="150" >
<cellValueFactory>
<PropertyValueFactory property="playtime" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Interpret" prefWidth="150">
<cellValueFactory>
<PropertyValueFactory property="interpret" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Album" prefWidth="150">
<cellValueFactory>
<PropertyValueFactory property="album" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Genre" prefWidth="150" >
<cellValueFactory>
<PropertyValueFactory property="genre" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Bewertung" prefWidth="60">
<cellValueFactory>
<PropertyValueFactory property="score" />
</cellValueFactory>
</TableColumn>
</columns>
This my Superclass for alle Mediatypes:
public abstract class Medium {
private static int id;
private String filepath;
private final Media mediaResource;
private final SimpleStringProperty titel = new SimpleStringProperty();
private final SimpleStringProperty genre = new SimpleStringProperty();
private final SimpleDoubleProperty score = new SimpleDoubleProperty();
protected Medium(String filepath, String titel, String genre, double score) {
setId(id++);
setFilepath(filepath);
setTitel(titel);
setGenre(genre);
setScore(score);
this.mediaResource = new Media(new File(getFilepath()).toURI().toString());
}
public static int getId() {
return id;
}
public static void setId(int id) {
Medium.id = id;
}
public final StringProperty titelProperty() {
return this.titel;
}
public String getTitel() {
return titelProperty().get();
}
public final void setTitel(String titel) {
titelProperty().set(titel);
}
public final StringProperty genreProperty() {
return this.genre;
}
public String getGenre() {
return genreProperty().get();
}
public final void setGenre(String genre) {
genreProperty().set(genre);
}
public final DoubleProperty scoreProperty() {
return this.score;
}
public double getScore() {
return scoreProperty().get();
}
public final void setScore(double score) {
scoreProperty().set(score);
}
public final String getFilepath() {
return this.filepath;
}
public final void setFilepath(String filepath) {
this.filepath = filepath;
}
public Media getMediaResource() {
return mediaResource;
}
}
This is the Music class:
public final class Music extends Medium {
private final SimpleStringProperty playtime = new SimpleStringProperty();
private final SimpleStringProperty interpret = new SimpleStringProperty();
private final SimpleStringProperty album = new SimpleStringProperty();
private final SimpleStringProperty genre = new SimpleStringProperty();
private final SimpleDoubleProperty score = new SimpleDoubleProperty();
/**
*
* #param titel
* #param playtime
* #param interpret
* #param album
* #param genre
* #param score
* #param filepath
*/
public Music(String titel,String playtime, String interpret,
String album, String genre, double score, String filepath) {
super(filepath, titel,genre, score);
setPlaytime(playtime);
setInterpret(interpret);
setAlbum(album);
}
public final StringProperty playtimeProperty() {
return this.playtime;
}
public String getPlaytime() {
return playtimeProperty().get();
}
public void setPlaytime(String playtime) {
playtimeProperty().set(playtime);
}
public final StringProperty interpretProperty() {
return this.interpret;
}
public String getInterpret() {
return interpretProperty().get();
}
public void setInterpret(String interpret) {
interpretProperty().set(interpret);
}
public final StringProperty albumProperty() {
return this.album;
}
public String getAlbum() {
return albumProperty().get();
}
public void setAlbum(String album) {
albumProperty().set(album);
}
}
And this is the controller which loads the data from the database into the tableview:
public final class MusicscreenController extends Controller implements Initializable {
#FXML
public TableView libraryNode;
#FXML
private MediaView mediaPlayerView;
/**
* Initialisiert die Bibliothek
*/
#Override
protected void initLibrary() {
try {
DatabaseConnector.connectTo("src/mediabox/database/database");
boolean setAll = libraryNode.getItems().addAll(DatabaseConnector.loadEntries("Music")); // Einträge der Datenbank
// auslesen und der library Node hinzufügen
} catch (SQLException | ConnectionException | NamingException | ClassNotFoundException ex) {
Logger.getLogger(MusicscreenController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
libraryNode = new TableView<Music>();
initLibrary();
libraryNode.requestFocus();
libraryNode.getSelectionModel().selectFirst();
}
#FXML
public void onLibraryRequest(KeyEvent e) {
if (e.getCode().equals(KeyCode.ENTER)) {
try {
MediaPlayerController mediaPlayerController = new MediaPlayerController((Music) libraryNode.getSelectionModel().getSelectedItem());
} catch (IOException ex) {
Logger.getLogger(MusicscreenController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
There is no error message or something like that. The TableView only shows "No content in TableView"
The DatabaseConnector class works fine. I tested if the loaded ArrayList contains the right data. I can't find an error in this code ... The AarrayList contains all the music objects, but the table don't represent them. So I think I got a problem in my design of the tableview.
-GhostfaceChilla-
Inside your initialize method, you are not supposed to use
libraryNode = new TableView<Music>();
All the components of Controller marked with #FXML are initialized while the FXML is loaded
Related
I am trying to create a simple Contacts Application in JavaFX. It has a main window with TableView and a DialogPane opening when I want to create new contact. In the DialogPane there are several TextFields from which I want to collect text in order to create a Contacts List. My problem is that when I want to read the input from the DialogPane (from TextFields), which is the separate fxml file with separate controller (separate from main Controller) the application runs an error (java.lang.NullPointerException). And when I put a TextField in my main window FXML file, then I can access this text from the textField just fine. Why do I get an error when I want to read data from DialogPane (Error-->File: Controller.java, I commented the section where I get an error)?? I am stuck. Can anyone suggest what am I doing wrong? Here is my code:
Main.java
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("mainwindow.fxml"));
primaryStage.setTitle("Your Contacts");
primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java
public class Controller {
#FXML
private BorderPane mainPanel;
public ObservableList<Contact> contactsList = FXCollections.observableArrayList();
#FXML
public void showAddContactDialog() {
Dialog<ButtonType> dialog = new Dialog<>();
dialog.initOwner(mainPanel.getScene().getWindow());
dialog.setTitle("Add new contact");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("addContactDialog.fxml"));
try {
dialog.getDialogPane().setContent(fxmlLoader.load());
} catch (IOException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(null);
alert.setContentText("Couldn't load the dialog");
alert.showAndWait();
e.printStackTrace();
return;
}
dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
Optional<ButtonType> result = dialog.showAndWait();
if(result.isPresent() && result.get() == ButtonType.OK) {
//========================================================================================
//here is the error, I cannot read values from addContactDialog controller
ContactController contactController = new ContactController();
String firstName = contactController.getNewContact().getFirstName();
String lastName = contactController.getNewContact().getLastName();
String phoneNumber = contactController.getNewContact().getPhoneNumber();
String emailAddress = contactController.getNewContact().getEmailAddress();
Contact newContact = new Contact(firstName, lastName, phoneNumber, emailAddress);
contactsList.add(newContact);
//or alternatively
// Contact newContact = contactController.getNewContact();
// contactsList.add(newContact);
//========================================================================================
}
}
}
ContactController.java
public class ContactController {
#FXML
private TextField firstNameField;
#FXML
private TextField lastNameField;
#FXML
private TextField phoneNumberFiled;
#FXML
private TextField emailField;
public Contact getNewContact() {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
String phoneNumber = phoneNumberFiled.getText();
String emailAddress = emailField.getText();
Contact newContact = new Contact(firstName, lastName, phoneNumber, emailAddress);
return newContact;
}
Contact.java
public class Contact {
private SimpleStringProperty firstName = new SimpleStringProperty("");
private SimpleStringProperty lastName = new SimpleStringProperty("");
private SimpleStringProperty phoneNumber = new SimpleStringProperty("");
private SimpleStringProperty emailAddress = new SimpleStringProperty("");
public Contact() {
}
public Contact(String firstName, String lastName, String phoneNumber, String emailAddress) {
this.firstName.set(firstName);
this.lastName.set(lastName);
this.phoneNumber.set(phoneNumber);
this.emailAddress.set(emailAddress);
}
public String getFirstName() {
return firstName.get();
}
public SimpleStringProperty firstNameProperty() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public String getLastName() {
return lastName.get();
}
public SimpleStringProperty lastNameProperty() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public String getPhoneNumber() {
return phoneNumber.get();
}
public SimpleStringProperty phoneNumberProperty() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber.set(phoneNumber);
}
public String getEmailAddress() {
return emailAddress.get();
}
public SimpleStringProperty emailAddressProperty() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress.set(emailAddress);
}
#Override
public String toString() {
return "Contact{" +
"firstName=" + firstName +
", lastName=" + lastName +
", phoneNumber=" + phoneNumber +
", emailAddress=" + emailAddress +
'}';
}
}
mainwindow.fxml
<BorderPane fx:id="mainPanel" fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml">
<top>
<MenuBar>
<menus>
<Menu text="Contacts">
<items>
<MenuItem text="Add new" onAction="#showAddContactDialog"/>
</items>
<items>
<MenuItem text="Edit" />
</items>
<items>
<MenuItem text="Delete"/>
</items>
<items>
<MenuItem text="Exit"/>
</items>
</Menu>
</menus>
<menus>
<Menu text="Info">
<items>
<MenuItem text="About"/>
</items>
</Menu>
</menus>
</MenuBar>
</top>
<center>
<TableView fx:id="contactsTable">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY"/>
</columnResizePolicy>
<columns>
<TableColumn text="First Name">
<cellValueFactory>
<PropertyValueFactory property="firstName"/>
</cellValueFactory>
</TableColumn>
<TableColumn text="Last Name">
<cellValueFactory>
<PropertyValueFactory property="lastName"/>
</cellValueFactory>
</TableColumn>
<TableColumn text="Phone Number">
<cellValueFactory>
<PropertyValueFactory property="phoneNumber"/>
</cellValueFactory>
</TableColumn>
<TableColumn text="Email">
<cellValueFactory>
<PropertyValueFactory property="emailAddress"/>
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
</center>
</BorderPane>
addContactDialog.fxml
<DialogPane fx:controller="sample.ContactController" xmlns:fx="http://javafx.com/fxml">
<headerText>
Fill in the information for the new Contact
</headerText>
<content>
<GridPane vgap="10" hgap="10">
<Label text="First Name: " GridPane.rowIndex="0" GridPane.columnIndex="0"/>
<TextField fx:id="firstNameField" GridPane.rowIndex="0" GridPane.columnIndex="1"/>
<Label text="Last Name: " GridPane.rowIndex="1" GridPane.columnIndex="0"/>
<TextField fx:id="lastNameField" GridPane.rowIndex="1" GridPane.columnIndex="1"/>
<Label text="Phone Number: " GridPane.rowIndex="2" GridPane.columnIndex="0"/>
<TextField fx:id="phoneNumberField" GridPane.rowIndex="2" GridPane.columnIndex="1"/>
<Label text="Notes: " GridPane.rowIndex="3" GridPane.columnIndex="0"/>
<TextField fx:id="notesField" GridPane.rowIndex="3" GridPane.columnIndex="1"/>
</GridPane>
</content>
</DialogPane>
Ok, I found the mistake - I made a typo in the ContactController.java file. It should have phoneNumberField instead of phoneNumberFiled String...
Did you tried putting .toString
like this
String firstName = contactController.getNewContact().getFirstName().toString();
This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 5 years ago.
javaFX: TableView's cellvalue is not enough to display in columns i can't solved, The following code executes, but the column is showing anything.
and display is like picture pict
this is Ligne_Commande class :
package pfe;
public class Ligne_Commande {
private int n_liv1;
private String des_art1;
private float prix_vent1;
private int qte_com1;
public Ligne_Commande(){
super();
}
public Ligne_Commande(String des_art, int qte_com, float prix_vent){
super();
this.des_art1= des_art;
this.prix_vent1= prix_vent;
this.qte_com1= qte_com;
}
public void setN_liv1(int n_liv) {
this.n_liv1 = n_liv;
}
public void setN_art1(String des_art) {
this.des_art1 = des_art;
}
public void setPrix_vent1(float prix_vent) {
this.prix_vent1 = prix_vent;
}
public void setQte_com1(int qte_com) {
this.qte_com1 = qte_com;
}
public int getN_liv1() {
return n_liv1;
}
public String getN_art1() {
return des_art1;
}
public float getPrix_vent1() {
return prix_vent1;
}
public int getQte_com1() {
return qte_com1;
}
}
and FXML controller :
#FXML
private TableView<Ligne_Commande> tableview_art_qte;
#FXML
private TableColumn<Ligne_Commande, String> col_art_commande;
#FXML
private TableColumn<Ligne_Commande, Integer> col_qte_commande;
#FXML
private TableColumn<Ligne_Commande, Float> col_prix_vent;
#Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList<Ligne_Commande> data = FXCollections.observableArrayList();
data.add(new Ligne_Commande("pommme", 100, 125));
col_art_commande.setCellValueFactory(new PropertyValueFactory<Ligne_Commande, String>("des_art1"));
col_qte_commande.setCellValueFactory(new PropertyValueFactory<Ligne_Commande, Integer>("qte_com1"));
col_prix_vent.setCellValueFactory(new PropertyValueFactory<Ligne_Commande, Float>("prix_vent1"));
tableview_art_qte.setItems(data);
}
FXML file :
<TableView fx:id="tableview_art_qte" editable="true" prefHeight="381.0" prefWidth="230.0" GridPane.columnIndex="2" GridPane.rowIndex="3">
<columns>
<TableColumn fx:id="col_art_commande" prefWidth="75.0" text="Article Commande" />
<TableColumn fx:id="col_qte_commande" maxWidth="2500.0" prefWidth="75.0" text="Qte Commande" />
<TableColumn fx:id="col_prix_vent" maxWidth="3000.0" prefWidth="75.0" text="Prix Vent" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
Your getter/setter methods getN_art1 and setN_art1 should be named getDes_art1 and setDes_art1, respectively. PropertyValueFactory<> searches for getters named getNameOfProperty.
See PropertyValueFactory<> documentation for details.
I can't figure out why my TableView is not setting the data. Seemingly everything is ok, but the rows just won't appear. i looked through tutorials, but I still don't see my error.Here is my code.
The data class:
package model.elastic;
import javafx.beans.property.SimpleStringProperty;
public class ElasticAttribute {
private SimpleStringProperty name;
private SimpleStringProperty type;
private SimpleStringProperty variable;
public ElasticAttribute(String name, String type, String variable) {
this.name = new SimpleStringProperty(name);
this.type = new SimpleStringProperty(type);
this.variable = new SimpleStringProperty(variable);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getType() {
return type.get();
}
public void setType(String type) {
this.type.set(type);
}
public String getVariable() {
return variable.get();
}
public void setVariable(String variable) {
this.variable.set(variable);
}
}
The controller:
#FXML
private TableView<ElasticAttribute> tableView;
private TableColumn tableColumnName;
private TableColumn tableColumnType;
private TableColumn tableColumnVariable;
public void initialize() {
final ObservableList<ElasticAttribute> data = FXCollections.observableArrayList(
new ElasticAttribute("Test", "Test", "Test"),
new ElasticAttribute("Test2", "Test", "Test"),
new ElasticAttribute("Test3", "Test", "Test"),
new ElasticAttribute("Test4", "Test", "Test"),
new ElasticAttribute("Test5", "Test", "Test")
);
tableColumnName = new TableColumn("Name");
tableColumnName.setCellValueFactory(
new PropertyValueFactory<ElasticAttribute, String>("name"));
tableColumnType = new TableColumn("Type");
tableColumnType.setCellValueFactory(
new PropertyValueFactory<ElasticAttribute, String>("type"));
tableColumnVariable = new TableColumn("Variable");
tableColumnVariable.setCellValueFactory(
new PropertyValueFactory<ElasticAttribute, String>("variable"));
tableView.setItems(data);
tableView.getColumns().addAll(tableColumnName, tableColumnType, tableColumnVariable);
The fxml:
<TableView fx:id="tableView" GridPane.rowIndex="1">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY"/>
</columnResizePolicy>
</TableView>
Thanks for help.
I have this TableView
<TableView fx:id="tableView">
<columns>
<TableColumn prefWidth="220.0" text="Source">
<cellValueFactory>
<PropertyValueFactory property="sourceContract" />
</cellValueFactory>
</TableColumn>
</columns>
<items>
<FXCollections fx:factory="observableArrayList">
<GridRowModel sourceContract="some contract" />
</FXCollections>
</items>
</TableView>
and these classes
public class GridRowModel {
private ObjectProperty<ContractConfig> sourceContract = new SimpleObjectProperty<>();
public GridRowModel() {
}
public ObjectProperty<ContractConfig> sourceContractProperty() {
return sourceContract;
}
public ContractConfig getSourceContract() {
return sourceContract.get();
}
public void setSourceContract(ContractConfig sourceContract) {
this.sourceContract.set(sourceContract);
}
}
public class ContractConfig {
private String name;
private String userFriendlyName;
public ContractConfig() {
}
public ContractConfig(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void setUserFriendlyName(String userFriendlyName) {
this.userFriendlyName = userFriendlyName;
}
public String getName() {
return name;
}
public String getUserFriendlyName() {
return userFriendlyName;
}
}
I get this obvious error:
Caused by: java.lang.IllegalArgumentException: Unable to coerce some contract to class com.ui.util.ContractConfig.
at com.sun.javafx.fxml.BeanAdapter.coerce(BeanAdapter.java:496)
at com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:258)
at com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:54)
I also tried this
public void setSourceContract(String sourceContract) {
ContractConfig cc = new ContractConfig();
cc.setUserFriendlyName(sourceContract);
this.sourceContract.set(cc);
}
But I get this error
Caused by: com.sun.javafx.fxml.PropertyNotFoundException: Property "sourceContract" does not exist or is read-only.
at com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:253)
at com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:54)
at javafx.fxml.FXMLLoader$Element.applyProperty(FXMLLoader.java:512)
Is it possible to use ObjectProperty with FXML values and if so, how can I use my ContractConfig object in the FXML?
You use the wrong fxml code for the class structure you've created. It should look like this instead:
<GridRowModel>
<sourceContract>
<ContractConfig name="some contract"/>
</sourceContract>
</GridRowModel>
You can also add a constructor with #NamedArg to GridRowModel and use
<GridRowModel sourceContract="some contract" />
private final ObjectProperty<ContractConfig> sourceContract;
private GridRowModel(ContractConfig sourceContract) {
this.sourceContract = new SimpleObjectProperty<>(sourceContract);
}
public GridRowModel() {
this((ContractConfig) null);
}
public GridRowModel(#NamedArg("sourceContract") String sourceContract) {
this(new ContractConfig(sourceContract));
}
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>