get string when selected from tableview javafx - java

So in basic form I want to get selected text from tableview.
I have my SetCoachFXML in which I have tableview, with some data in it. Next to that I have choose button. How can I get selected text from tableview when I click on choose button?
http://imgur.com/wA6n792
I tried suggestion from here but I get nothing.
Here is my setcoach controller class:
public class SetCoachController implements Initializable {
//Kolone i tabela za prikazivanje trenera
#FXML
private TableColumn<Coaches, String> coachesNameCol;
#FXML
private TableColumn<Coaches, String> coachesLNCol;
#FXML
private TableView<Coaches> coachTable;
#FXML
private Button chooseBtn;
#FXML
private Button cancelBtn;
private ObservableList<Coaches> coachesData;
#Override
public void initialize(URL url, ResourceBundle rb) {
coachesNameCol
.setCellValueFactory(new PropertyValueFactory<Coaches, String>(
"name"));
coachesLNCol
.setCellValueFactory(new PropertyValueFactory<Coaches, String>(
"lastName"));
coachesData = FXCollections.observableArrayList();
coachTable.setItems(coachesData);
coachTable.setEditable(false);
CoachBase.get();
loadCoachesData();
}
//sql upit
public void loadCoachesData() {
try {
ResultSet rs = CoachBase.query("SELECT * FROM CoachTable");
coachesData.clear();
while (rs.next()) {
coachesData.add(new Coaches(rs.getString("Name"), rs.getString("Lastname")));
}
} catch (Exception e) {
System.out.println("" + e.getMessage());
}
}
public void chooseAction(ActionEvent event) {
Coaches coach = (Coaches) coachTable.getSelectionModel().getSelectedItem();
System.out.println(coach.getcoachesName());
}
public void cancelAction(ActionEvent event) {
Stage stage = (Stage) cancelBtn.getScene().getWindow();
stage.close();
}
and my Coaches class:
public class Coaches {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty name = new SimpleStringProperty();
private SimpleStringProperty lastName = new SimpleStringProperty();
private SimpleIntegerProperty age = new SimpleIntegerProperty();
public Coaches(Integer id, String name, String lastName, int age) {
this.name.setValue(name);
this.lastName.setValue(lastName);
this.age.setValue(age);
}
public Coaches(String name, String lastName) {
this.name.setValue(name);
this.lastName.setValue(lastName);
}
public Integer getId() {
if (id == null) {
return 0;
}
return id.getValue();
}
public String getcoachesName() {
if (name != null) {
return "";
}
return name.getValueSafe();
}
public String getlastName() {
if (lastName != null) {
return "";
}
return lastName.getValueSafe();
}
public Integer getAge() {
if (age == null) {
return 0;
}
return age.getValue();
}
public SimpleIntegerProperty IdProperty() {
return id;
}
public SimpleStringProperty nameProperty() {
return name;
}
public SimpleStringProperty lastNameProperty() {
return lastName;
}
public SimpleIntegerProperty ageProperty() {
return age;
}
}

I think what's happening is when you click on the button, your loosing focus on the selected cell which means when you try to retrieving data, nothing happens.
What you need to do is make sure that when you click on the button, the cell/row is still selected.
Then you can do something like:
// To retrieve
Person person = (Person)taview.getSelectionModel().getSelectedItem();
System.out.println(person.getName());

Related

How to receive data in particular row of tableView in javafx?

I am working on rfid and I am receiving data in tableView from database mysql which matches the UID of my rfid tag.
But when I tap the another RFid tag, the previous data is overwritten by the new one.
But I want the new data in next row of tableview.
This is my Controller code:
public class detectController {
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private TableView<detectBean> tableView;
#FXML
private TextField txtSTID;
ObservableList<detectBean> list;
public static SerialPort s1;
static String temp="";
static String temp1="";
static void doAlert(String msg)
{
Alert alert=new Alert(AlertType.INFORMATION);
alert.setTitle("Alert..");
alert.setContentText(msg);
alert.show();
}
ObservableList<detectBean> getRecordsFromTableSome(String sID) throws FileNotFoundException
{
list=FXCollections.observableArrayList();
try {
pst=con.prepareStatement("select * from stuRegis where studentID=?");
pst.setString(1, sID);
ResultSet rs= pst.executeQuery();
while(rs.next())
{
String studentID=rs.getString("studentID");
String name=rs.getString("name");
String sroll=rs.getString("sroll");
String clas=rs.getString("clas");
String fname=rs.getString("fname");
String contact=rs.getString("contact");
String pic = rs.getString("pic");
FileInputStream photo=new FileInputStream(pic);
Image image1 = new Image(photo, 100, 100, false, false);
detectBean bean=new detectBean(studentID, name, sroll, clas, fname, contact, new ImageView(image1));
list.add(bean);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/////////////////////////////////////////////////////
#FXML
void doFetch(ActionEvent event) throws IOException{
String a = recall();
txtSTID.setText(a);
ObservableList<detectBean> list=getRecordsFromTableSome(a);
tableView.setItems(list);
}
#FXML
void doComClose(ActionEvent event) {
if(s1.closePort()){
doAlert("Port Closed");
System.out.println("Port closed successFully");
}else{
doAlert("Failed to Close Port");
System.out.println("Failed to close port");
}
}
#FXML
void doOpenCom(ActionEvent event) {
port();
}
/////////////////////////////////////////////////////
public static void port()
{
SerialPort[] s=SerialPort.getCommPorts();
for(SerialPort port:s){
System.out.println(""+port.getSystemPortName());
s1=SerialPort.getCommPort(port.getSystemPortName());
if(s1.openPort()){
doAlert("Port Opened");
System.out.println("Port opened successFully ");
}else{
doAlert("Failed to Open Port");
System.out.println("Failed to open port");
}
}
s1.setBaudRate(9600);
}
public static String recall() throws IOException
{
InputStream is=s1.getInputStream();
StringBuilder st = new StringBuilder();
for(int i=0,x=0;true;i++){
//for (int i =0;i<11;i++){
st=st.append((char)is.read());
temp1=st.toString();
if(temp1.length()==13)
{ System.out.print(temp1);
//System.out.print(temp);
//System.out.print(temp1.length());
break;
}
System.out.print(temp1);
}
//System.out.print(""+(char)is.read());
temp=temp1.substring(0,11);
System.out.print(temp.length());
System.gc();
return temp;
}
//////////////////////////////////////////////////////
PreparedStatement pst;
Connection con;
#FXML
void initialize() throws IOException, FileNotFoundException {
con=MysqlConnection.doConnect();
TableColumn<detectBean, String> studentID=new TableColumn<detectBean, String>("Student ID");//Dikhava Title
studentID.setCellValueFactory(new PropertyValueFactory<>("studentID"));//bean field name
studentID.setMinWidth(90);
TableColumn<detectBean, String> name=new TableColumn<detectBean, String>("Name");//Dikhava Title
name.setCellValueFactory(new PropertyValueFactory<>("name"));//bean field name
TableColumn<detectBean, String> sroll=new TableColumn<detectBean, String>("Roll No.");//Dikhava Title
sroll.setCellValueFactory(new PropertyValueFactory<>("sroll"));//bean field name
TableColumn<detectBean, String> clas=new TableColumn<detectBean, String>("Class");//Dikhava Title
clas.setCellValueFactory(new PropertyValueFactory<>("clas"));//bean field name
TableColumn<detectBean, String> fname=new TableColumn<detectBean, String>("Father's Name");//Dikhava Title
fname.setCellValueFactory(new PropertyValueFactory<>("fname"));//bean field name
TableColumn<detectBean, String> contact=new TableColumn<detectBean, String>("Contact No.");//Dikhava Title
contact.setCellValueFactory(new PropertyValueFactory<>("contact"));//bean field name
contact.setMinWidth(90);
TableColumn<detectBean, Image> pic=new TableColumn<detectBean, Image>("Image");//Dikhava Title
pic.setCellValueFactory(new PropertyValueFactory<>("pic"));//bean field name
pic.setMinWidth(110);
tableView.getColumns().clear();
tableView.getColumns().addAll(studentID,name,sroll,clas,fname,contact,pic);
}
}
DetectBean :
public class detectBean {
String studentID;
String name;
String sroll;
String clas;
String fname;
String contact;
ImageView image;
public detectBean(String studentID, String name, String sroll, String clas, String fname, String contact, ImageView image) {
super();
this.studentID = studentID;
this.name = name;
this.sroll = sroll;
this.clas = clas;
this.fname = fname;
this.contact = contact;
this.image = image;
}
public String getsID() {
return studentID;
}
public void setsID(String studentID) {
this.studentID = studentID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSroll() {
return sroll;
}
public void setSroll(String sroll) {
this.sroll = sroll;
}
public String getClas() {
return clas;
}
public void setClas(String clas) {
this.clas = clas;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public ImageView getPic() {
return image;
}
public void setPic(String pic) {
this.image = image;
}
}
Image of output:
not displaying data in student ID column
I think the Problem is:
tableView.setItems(list);
resets the list.
try instead :
tableview.getItems().addAll(list);
Alternatively only set an ObservableList in the initialize method and change that list directly in you query.
public class detectController {
//....
#FXML
private TableView<detectBean> tableView;
ObservableList<detectBean> list;
///....
/////////////////////////////////////////////////////
#FXML
void doFetch(ActionEvent event) throws IOException{
String a = recall();
txtSTID.setText(a);
ObservableList<detectBean> list=getRecordsFromTableSome(a);
/// here!!!
// tableView.setItems(list);
tableView.getItems().addAll(list);
}

javafx - How to get a cell value of selected row

I am trying to solve a basic problem. Could you please have a look at this code and push me forward a little bit?
I have this
public class StrediskoController {
private Stage dialogStage;
#FXML private TableView strediskaTableView = new TableView<>();
#FXML private Label nameLabel;
private ObservableList<Stredisko> data = FXCollections.observableArrayList();
#FXML public void initialize() {
System.out.println("test");
strediskaTableView.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
//Check whether item is selected and set value of selected item to Label
if (strediskaTableView.getSelectionModel().getSelectedItem() != null) {
nameLabel.setText(".....");
}
});
}
public void setDialogStage(Stage dialogStage) { this.dialogStage = dialogStage; }
public void GetStrediska() {
new StrediskoDAO().SeeAllStredisko(data, strediskaTableView);
}
I want to select a row in tableview and put a value of second column into label.
My StrediskoDAO looks like:
public void SeeAllStredisko(ObservableList data, TableView<Stredisko> stredisko)
{
try
{
String select = "Select * from stredisko";
PreparedStatement stmt = DatabaseConnection.prepareStatement(select);
ResultSet rst = stmt.executeQuery();
for(int i=0 ; i<rst.getMetaData().getColumnCount(); i++){
//using non property style for making dynamic table
final int j = i;
TableColumn col = new TableColumn(rst.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
stredisko.getColumns().addAll(col);
System.out.println("Column ["+i+"] ");
}
while(rst.next())
{
ObservableList<String> row = FXCollections.observableArrayList();
for (int i = 1; i <= rst.getMetaData().getColumnCount(); i++)
{
row.add(rst.getString(i));
System.out.println(row);
}
data.add(row);
}
stredisko.setItems(data);
}
catch(ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
}
and Stredisko
public class Stredisko {
private SimpleIntegerProperty stredisko_Id;
private SimpleStringProperty name;
public Stredisko(int stredisko_Id, String name) {
this.stredisko_Id = new SimpleIntegerProperty(stredisko_Id);
this.name = new SimpleStringProperty(name);
}
public int getStredisko_Id() {
return stredisko_Id.get();
}
public SimpleIntegerProperty stredisko_IdProperty() {
return stredisko_Id;
}
public void setStredisko_Id(int stredisko_Id) {
this.stredisko_Id.set(stredisko_Id);
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
I am just a beginner in JavaFX and I would be really happy if you help me :-)
Thank you guys.

Vaadin field group is not working

I am trying to implement vaadin fieldgroup but it does not bind the values.
And it is giving me the following error :
Communication problem
Invalid JSON response from server:
Here is my code.
Model Class:
public class LoggedCustomer {
private String Id;
private String Name;
private String Cell;
private String email;
private String address;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getCell() {
return Cell;
}
public void setCell(String cell) {
Cell = cell;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Customer Layout Class:
public class CustomerFormView extends FormLayout {
#PropertyId("id")
private TextField id = new TextField("Customer Id");
#PropertyId("name")
private TextField name = new TextField("Customer Name");
#PropertyId("cell")
private TextField cell = new TextField("Customer Cell Number");
#PropertyId("email")
private TextField email = new TextField("Customer Email");
#PropertyId("address")
private TextField address = new TextField("Customer Address");
public CustomerFormView() {
setSpacing(true);
addComponent(id);
addComponent(name);
addComponent(cell);
addComponent(email);
addComponent(address);
}
}
Main UI Class:
public class LoggedIn extends UI {
#WebServlet(value = "/loggedin", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = LoggedIn.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
HorizontalLayout hori = new HorizontalLayout();
setContent(hori);
hori.setSpacing(true);
hori.setMargin(true);
Item customer = createCustomer();
hori.addComponent(createView(customer));
hori.addComponent(displayCustomer(customer));
}
private Layout createView(Item item) {
VerticalLayout formLayout = new VerticalLayout();
formLayout.setMargin(true);
formLayout.setSizeFull();
CustomerFormView productEditLayout = new CustomerFormView();
formLayout.addComponent(productEditLayout);
final FieldGroup binder = new FieldGroup(item);
binder.bindMemberFields(productEditLayout);
HorizontalLayout footer = new HorizontalLayout();
footer.setSpacing(true);
footer.addComponent(new Button("Save", new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
try {
binder.commit();
} catch (InvalidValueException e) {
} catch (CommitException e) {
}
}
}));
footer.addComponent(new Button("Cancel", new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
binder.discard();
}
}));
formLayout.addComponent(footer);
return formLayout;
}
private Layout displayCustomer(Item item) {
FormLayout layout = new FormLayout();
Label name = new Label();
name.setPropertyDataSource(item.getItemProperty("name"));
name.setCaption("Name");
layout.addComponent(name);
return layout;
}
private static Item createCustomer() {
LoggedCustomer customer = new LoggedCustomer();
customer.setName("");
customer.setId("");
customer.setCell("");
customer.setEmail("");
customer.setAddress("");
return new BeanItem<LoggedCustomer>(customer);
}
}
this is the full code of my application in which I am working but the fieldgroup binder is not working and giving the error.
Kindly someone help me to identify where is the problem and what i am doing wrong in the code.
I shall be thankful.... :)

TableVew - Select and focus clicked cell

I have an event listener on a TableView which listens for mouse events. How can I get the mouse clicked cell index (and change focus to the new cell) when a mouse event is thrown.
public class PrnTableController
{
#FXML
private TableView<SimpleStringProperty> table;
#FXML
private TableColumn<SimpleStringProperty, String> data;
#FXML
private void initialize()
{
this.data.setCellValueFactory(cellData -> cellData.getValue());
this.data.setCellFactory(event -> new EditCell(this.observablePrnPropertyData, this.table));
// Add mouse Listener
this.table.setOnMouseClicked(event -> this.handleOnMouseClick(event));
}
private void handleOnMouseClick(MouseEvent event)
{
TableView tv = (TableView) event.getSource();
// TODO : get the mouse clicked cell index
int index = ???
if (event.getButton().equals(MouseButton.PRIMARY))
{
if (event.getClickCount() == 2)
{
LOGGER.info("Double clicked on cell");
final int focusedIndex = this.table.getSelectionModel().getFocusedIndex();
if (index == focusedIndex)
{
// TODO : Double click
}
}
else if (event.getClickCount() == 1)
{
// TODO : Single click
}
}
}
}
I have managed to get the clicked cell index when the mouse event is on the Cell but not the table.
The following code can be used to get the clicked cell index when the event is on the Cell. I've had problems with selecting and changing focus when the mouse event is on TabelCell. The focus does not change to the new cell. It changes if you double click. With a single click nothing happens. I suspect thats because I have other event listeners, there may be conflicting events. I have the following event on the TableCell - setOnDragDetected, setOnMouseDragEntered and the following event on the TableView - addEventFilter, setOnKeyPressed, setOnEditCommit.
TableCell<Map<String, SimpleStringProperty>, String> cell = (TableCell<Map<String, SimpleStringProperty>, String>) mouseEvent.getSource();
int index = cell.getIndex();
Here is an example with the problem. Basically when you click on an cell, you can see that the event is registered but nothing happens. I mean the focus does change to the newly clicked cell.
public class TableViewEditOnType extends Application
{
private TableView<Person> table;
private ObservableList<Person> observableListOfPerson;
#Override
public void start(Stage primaryStage)
{
this.table = new TableView<>();
this.table.getSelectionModel().setCellSelectionEnabled(true);
this.table.setEditable(true);
TableColumn<Person, String> firstName = this.createColumn("First Name", Person::firstNameProperty);
TableColumn<Person, String> lastName = this.createColumn("Last Name", Person::lastNameProperty);
TableColumn<Person, String> email = this.createColumn("Email", Person::emailProperty);
this.table.getColumns().add(firstName);
this.table.getColumns().add(lastName);
this.table.getColumns().add(email);
this.observableListOfPerson = FXCollections.observableArrayList();
this.observableListOfPerson.add(new Person("Jacob", "Smith", "jacob.smith#example.com"));
this.observableListOfPerson.add(new Person("Isabella", "Johnson", "isabella.johnson#example.com"));
this.observableListOfPerson.add(new Person("Ethan", "Williams", "ethan.williams#example.com"));
this.observableListOfPerson.add(new Person("Emma", "Jones", "emma.jones#example.com"));
this.observableListOfPerson.add(new Person("Michael", "Brown", "michael.brown#example.com"));
this.table.getItems().addAll(this.observableListOfPerson);
firstName.setOnEditCommit(event -> this.editCommit(event, "firstName"));
lastName.setOnEditCommit(event -> this.editCommit(event, "lastName"));
email.setOnEditCommit(event -> this.editCommit(event, "email"));
this.table.setOnKeyPressed(event -> {
TablePosition<Person, ?> pos = this.table.getFocusModel().getFocusedCell();
if (pos != null)
{
this.table.edit(pos.getRow(), pos.getTableColumn());
}
});
Scene scene = new Scene(new BorderPane(this.table), 880, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private void editCommit(CellEditEvent<Person, String> event, String whatEdited)
{
if (whatEdited.equals("firstName"))
{
event.getTableView().getItems().get(event.getTablePosition().getRow()).setFirstName(event.getNewValue());
}
else if (whatEdited.equals("lastName"))
{
event.getTableView().getItems().get(event.getTablePosition().getRow()).setLastName(event.getNewValue());
}
else if (whatEdited.equals("email"))
{
event.getTableView().getItems().get(event.getTablePosition().getRow()).setEmail(event.getNewValue());
}
}
private TableColumn<Person, String> createColumn(String title, Function<Person, StringProperty> property)
{
TableColumn<Person, String> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
col.setCellFactory(column -> new EditCell(property, this.table, this.observableListOfPerson));
return col;
}
private static class EditCell extends TableCell<Person, String>
{
private final TextField textField = new TextField();
private final Function<Person, StringProperty> property;
private TableView table;
private ObservableList<Person> observableListOfPerson;
EditCell(Function<Person, StringProperty> property, TableView table, ObservableList<Person> observableListOfPerson)
{
this.property = property;
this.table = table;
this.observableListOfPerson = observableListOfPerson;
this.textProperty().bind(this.itemProperty());
this.setGraphic(this.textField);
this.setContentDisplay(ContentDisplay.TEXT_ONLY);
this.textField.setOnAction(evt -> {
this.commitEdit(this.textField.getText());
});
this.textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
if (!isNowFocused)
{
this.commitEdit(this.textField.getText());
}
});
// On mouse click event
this.setOnMouseClicked(mouseEvent -> this.handleCellMouseClick(mouseEvent));
}
private void handleCellMouseClick(final MouseEvent mouseEvent)
{
System.out.println("MOUSE EVENT");
TableCell<Map<String, SimpleStringProperty>, String> cell = (TableCell<Map<String, SimpleStringProperty>, String>) mouseEvent.getSource();
int index = cell.getIndex();
// Set up the map data structure before editing
this.validCell(index);
if (mouseEvent.getButton().equals(MouseButton.PRIMARY))
{
if (mouseEvent.getClickCount() == 2)
{
System.out.println("Double clicked on cell");
final int focusedIndex = this.table.getSelectionModel().getFocusedIndex();
if (index == focusedIndex)
{
this.changeTableCellFocus(this.table, index);
}
}
else if (mouseEvent.getClickCount() == 1)
{
System.out.println("Single click on cell");
this.changeTableCellFocus(this.table, index);
}
}
}
private void validCell(final int cellIndex)
{
if (cellIndex >= this.observableListOfPerson.size())
{
for (int x = this.observableListOfPerson.size(); x <= cellIndex; x++)
{
this.observableListOfPerson.add(new Person("", "", ""));
}
}
}
public void changeTableCellFocus(final TableView<?> table, final int focusIndex)
{
table.requestFocus();
table.getSelectionModel().clearAndSelect(focusIndex);
table.getFocusModel().focus(focusIndex);
}
#Override
public void startEdit()
{
super.startEdit();
this.textField.setText(this.getItem());
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.textField.requestFocus();
}
#Override
public void cancelEdit()
{
super.cancelEdit();
this.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
#Override
public void commitEdit(String text)
{
super.commitEdit(text);
Person person = this.getTableView().getItems().get(this.getIndex());
StringProperty cellProperty = this.property.apply(person);
cellProperty.set(text);
this.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
public static class Person
{
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
private final StringProperty email = new SimpleStringProperty();
public Person(String firstName, String lastName, String email)
{
this.setFirstName(firstName);
this.setLastName(lastName);
this.setEmail(email);
}
public final StringProperty firstNameProperty()
{
return this.firstName;
}
public final java.lang.String getFirstName()
{
return this.firstNameProperty().get();
}
public final void setFirstName(final java.lang.String firstName)
{
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty()
{
return this.lastName;
}
public final java.lang.String getLastName()
{
return this.lastNameProperty().get();
}
public final void setLastName(final java.lang.String lastName)
{
this.lastNameProperty().set(lastName);
}
public final StringProperty emailProperty()
{
return this.email;
}
public final java.lang.String getEmail()
{
return this.emailProperty().get();
}
public final void setEmail(final java.lang.String email)
{
this.emailProperty().set(email);
}
}
public static void main(String[] args)
{
launch(args);
}
}
Try this :
TableCell tc = (TableCell) event.getSource();
int index = tc.getIndex();

Building TreeView out of compsition between Set and Entity

I want to use a TreeView to display categories and actual content. I used this tutorial to follow my example, since they do something similiar but they simplify it.
I have something like this
public class Category {
final StringProperty categoryName = new SimpleStringProperty();
final ListProperty<Contact> contactList = new SimpleListProperty<>(FXCollections.<Contact>observableArrayList());
public Category(String name, List<Contact> contactList) {
this.categoryName.set(name);
this.contactList.setAll(contactList);
}
public StringProperty categoryNameProperty() { return this.categoryName; }
public ListProperty<Contact> contactListProperty() { return this.contactList; }
}
public class Contact {
final StringProperty contactName = new SimpleStringProperty();
public Contact(String name) {
this.contactName.set(name);
}
public StringProperty contactNameProperty() { return this.contactName; }
}
And now I want to build a TreeView out of a List<Category> with the underlying contacts automatically inserted as child nodes. Is this possible? If possible I would like not modify the Model itself. I thought of extending TreeItem<T> but I am not sure how far this will get me.
Ok I solved this with this, somebody by change a better solution?
public class Main extends Application {
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setWidth(300);
stage.setHeight(500);
final TreeView<MailTreeItem> tree = new TreeView<>();
final List<Category> categoryList = FXCollections.observableArrayList();
tree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<MailTreeItem>>() {
#Override
public void changed(
ObservableValue<? extends TreeItem<MailTreeItem>> observable,
TreeItem<MailTreeItem> oldValue,
TreeItem<MailTreeItem> newValue) {
newValue.getValue();
}
});
final List<Contact> categoryContact1List = FXCollections.observableArrayList();
categoryContact1List.add(new Contact("Hans"));
categoryContact1List.add(new Contact("Dieter"));
final List<Contact> categoryContact2List = FXCollections.observableArrayList();
categoryContact2List.add(new Contact("Peter"));
categoryList.add(new Category("Freunde", categoryContact1List));
categoryList.add(new Category("Feinde", categoryContact2List));
final TreeItem<MailTreeItem> root = new TreeItem<MailTreeItem>(new RootTreeItem());
root.setExpanded(true);
tree.setRoot(root);
for (Category category : categoryList) {
final List<Contact> contactList = category.contactListProperty().get();
final TreeItem<MailTreeItem> categoryTreeItem = new TreeItem<MailTreeItem>(new CategoryTreeItem(category));
for (Contact contact : contactList) {
categoryTreeItem.getChildren().add(new TreeItem<MailTreeItem>(new ContactTreeItem(contact)));
}
root.getChildren().add(categoryTreeItem);
}
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(tree);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
public interface MailTreeItem {
public boolean isCategory();
public boolean isContact();
public Category getCategory();
public Contact getContact();
}
public class RootTreeItem implements MailTreeItem {
#Override public String toString() { return "root"; }
#Override public boolean isCategory() { return false; }
#Override public boolean isContact() { return false; }
#Override public Category getCategory() { return null; }
#Override public Contact getContact() { return null; }
}
public class CategoryTreeItem implements MailTreeItem {
private ObjectProperty<Category> category = new SimpleObjectProperty<>();
public CategoryTreeItem(Category category) {
this.category.set(category);
}
public ObjectProperty<Category> categoryProperty() { return this.category; }
#Override public String toString() { return this.category.get().categoryNameProperty().get(); }
public boolean isCategory() { return true; }
public boolean isContact() { return false; }
public Category getCategory() { return this.category.get(); }
public Contact getContact() { return null; }
}
public class ContactTreeItem implements MailTreeItem {
private final ObjectProperty<Contact> contact = new SimpleObjectProperty<>();
public ContactTreeItem(Contact contact) {
this.contact.set(contact);
}
public ObjectProperty<Contact> contactProperty() { return this.contact; }
#Override public String toString() { return this.contact.get().contactNameProperty().get(); }
public boolean isCategory() { return false; }
public boolean isContact() { return true; }
public Category getCategory() { return null; }
public Contact getContact() { return this.contact.get(); }
}
public class Category {
private final StringProperty categoryName = new SimpleStringProperty();
private final ListProperty<Contact> contactList = new SimpleListProperty<>(FXCollections.<Contact>observableArrayList());
public Category(String name, List<Contact> contactList) {
this.categoryName.set(name);
this.contactList.setAll(contactList);
}
public StringProperty categoryNameProperty() { return this.categoryName; }
public ListProperty<Contact> contactListProperty() { return this.contactList; }
}
public class Contact {
private final StringProperty contactName = new SimpleStringProperty();
public Contact(String name) {
this.contactName.set(name);
}
public StringProperty contactNameProperty() { return this.contactName; }
}
}

Categories