javafx - How to get a cell value of selected row - java

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.

Related

adding button to javafx table view with condition

I am new to javafx and working on to add Button to TableView with condition .
if the condition is true it will add the button and if false the button will not add to the tableView . i google it but i did not find any suggetion or solution .
is there any way to achieve it. thank in advance.
here is my controller
#FXML
TableView<Employee> employeeTable;
#FXML
TableColumn<Employee, Integer> col_id;
#FXML
TableColumn<Employee, String> col_fatherName;
#FXML
TableColumn<Employee, String> col_CNIC;
#FXML
TableColumn<Employee, String> col_gender;
#FXML
TableColumn<Employee, Button> update;
List<Employee> employees = new ArrayList<>();
ObservableList<Employee> obs = FXCollections.observableArrayList();
private Employee data;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
setColumnProperties();
addButtonToTable();
addDeleteButton();
loadData();
}
private void loadData() {
employees = employeeDAO.findAllEmployees();
obs = FXCollections.observableArrayList(employees);
employeeTable.getItems().clear();
employeeTable.getItems().addAll(obs);
}
public void setColumnProperties() {
col_id.setCellValueFactory(new PropertyValueFactory<Employee, Integer>("id"));
col_fatherName.setCellValueFactory(new PropertyValueFactory<Employee, String>("fatherName"));
col_CNIC.setCellValueFactory(new PropertyValueFactory<Employee, String>("cnic"));
col_gender.setCellValueFactory(new PropertyValueFactory<Employee, String>("name"));
}
private void addButtonToTable() {
Callback<TableColumn<Employee, Button>, TableCell<Employee, Button>> cellFactory = new Callback<TableColumn<Employee, Button>, TableCell<Employee, Button>>() {
#Override
public TableCell<Employee, Button> call(final TableColumn<Employee, Button> param) {
final TableCell<Employee, Button> cell = new TableCell<Employee, Button>() {
Image imgEdit = new Image(getClass().getResourceAsStream("/images/download.png"));
{
}
#Override
public void updateItem(Button item, boolean empty) {
super.updateItem(item, empty);
edite=new Button("Btn"); // global btn
if (empty) {
setGraphic(null);
} else {
// here i am trying to write condition
Iterator ite= employeeDAO.findAllEmployees().iterator();
while (ite.hasNext()){
Employee employee=(Employee) ite.next();
if (employee.getName().equals("jnk"))
{
edite.setOnAction((ActionEvent event) -> {
System.out.println( edite.getId());
data = getTableView().getItems().get(getIndex());
fatherName.setText(data.getFatherName());
CNIC.setText(data.getCnic());
name.setText(data.getName());
register_btn.setText("Update");
});
edite.setStyle("-fx-background-color: transparent;");
ImageView iv = new ImageView();
iv.setFitHeight(50);
iv.setFitWidth(50);
iv.setImage(imgEdit);
iv.setPreserveRatio(true);
iv.setSmooth(true);
iv.setCache(true);
edite.setGraphic(iv);
setGraphic(edite);
setText(null);
}
else{
System.out.println("not working");
}
}
}
}
};
return cell;
}
;
};
update.setCellFactory(cellFactory);
employeeTable.getColumns().add(update);
register_btn.setText("Register");
}
my goal is add the button if the Name='jnk'
but after the condition is true it add buttons to all row.
My Employee Class
public class EMployee{
private int id;
private String name;
private String cnic;
private String skill;
private String dob;
private String fatherName;
private String gender;
private int value;
setter and getter
}
EmployeeDao Class is
Public Class EmployeeDAO extends JdbcDaoSupport {
public List<Employee> findAllEmployees() {
List<Employee> empList = new ArrayList<>();
String query = "select * from employee";
getJdbcTemplate().query(query,
new BeanPropertyRowMapper<Employee>(Employee.class));
return empList;
}
}

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);
}

Howto customize TableCell/TableColumn content according to its row element in TableView (JavaFX)

Issue
I have a TableColumn<User, String> colPassword which currently only display existing passwords (String) as masked for each entry (row).
Needs
I need your help, so that each TableCell only shows the masked password if the user for the respective row: user.isManager == true, otherwise the password should be unmasked.
My current approach
I will provide only the crucial parts to ease the understanding.
public class User implements Serializable {
private Long id;
private boolean deleted = false;
private final BooleanProperty manager = new SimpleBooleanProperty();
private final StringProperty password = new SimpleStringProperty("");
public User() {
}
public boolean isManager() {
return manager.get();
}
public void setManager(boolean value) {
manager.set(value);
}
public BooleanProperty managerProperty() {
return manager;
}
UserController for GUI
public class UsersController {
#FXML
private TableView<User> tblUsers;
#FXML
private TableColumn<User, String> colPassword;
private void initTableColumns() {
colPassword.setCellValueFactory(cellData
-> cellData.getValue().passwordProperty()
);
colPassword.setCellFactory((TableColumn<User, String> param) -> {
return new PasswordFieldCell();
});
}
here is the custom TabelCell
public class PasswordFieldCell extends TableCell<User, String> {
private final Label lbl;
public PasswordFieldCell() {
lbl = new Label();
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setGraphic(null);
}
private String generatePasswordString(int len) {
String dots = "";
for (int i = 0; i < len; i++) {
dots += "*";
}
return dots;
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
lbl.setText(generatePasswordString(item.length()));
setGraphic(lbl);
} else {
setGraphic(null);
}
}
}
Solution
With help of VGR I was able to come up with this solution in PasswordFieldCell.
public class PasswordFieldCell extends TableCell<User, String> {
private final Label lbl;
public PasswordFieldCell() {
lbl = new Label();
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setGraphic(null);
}
private String generatePasswordString(int len) {
String dots = "";
for (int i = 0; i < len; i++) {
dots += "*";
}
return dots;
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
int row = getIndex();
User user = getTableView().getItems().get(row);
if (user.isManager()) { // mask password
lbl.setText(generatePasswordString(item.length()));
} else { // unmask password
lbl.setText(item);
}
setGraphic(lbl);
} else {
setGraphic(null);
}
}
}
Your PasswordFieldCell class inherits a lot of useful methods from TableCell.
In particular, you inherit a getTableView() method, and a getIndex() method which returns the row of the current cell. Those are all you need to look up the cell’s row value in your updateItem method:
int row = getIndex();
User user = getTableView().getItems().get(row);

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();

get string when selected from tableview javafx

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());

Categories