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; }
}
}
Related
I have 3 classes the first one is Library Item this is the super class. The other two classes are Book and Movie. When I want to fill my table view I want to make sure the correct property is called when populating the table view. I know it is easier to just call the director and author the same for ease of use, but I want to get it working for learning purposes. I have left out packages and imports for relevance.
LibraryItem class
public abstract class LibraryItem {
private int itemCode;
private String title;
private boolean availability;
private int memberIdentifier;
private LocalDate dateLent;
protected LibraryItem(int itemCode, String title, boolean availability, int memberIdentifier, LocalDate dateLent) {
this.itemCode = itemCode;
this.title = title;
this.availability = availability;
this.memberIdentifier = memberIdentifier;
this.dateLent = dateLent;
}
public int getItemCode() {
return itemCode;
}
public String getTitle() {
return title;
}
public boolean isAvailability() {
return availability;
}
public void setAvailability(boolean availability) {
this.availability = availability;
}
public int getMemberIdentifier() {
return memberIdentifier;
}
public void setMemberIdentifier(int memberIdentifier) {
this.memberIdentifier = memberIdentifier;
}
public LocalDate getDateLent() {
return dateLent;
}
public void setDateLent(LocalDate dateLent) {
this.dateLent = dateLent;
}
}
Book class
public class Book extends LibraryItem {
private String author;
protected Book(int itemCode, String title, boolean isLent, int memberIdentifier, LocalDate dateLent, String author) {
super(itemCode, title, isLent, memberIdentifier, dateLent);
this.author = author;
}
}
Movie class
public class Movie extends LibraryItem {
private String director;
protected Movie(int itemCode, String title, boolean isLent, int memberIdentifier, LocalDate dateLent, String director) {
super(itemCode, title, isLent, memberIdentifier, dateLent);
this.director = director;
}
}
I was thinking maybe there is some kind of check I can do for each row implemented so the correct value will be given,
This was my attempt:
public class CollectionController implements Initializable {
#FXML
private TableView<LibraryItem> libraryItemsTable;
#FXML
private TableColumn<LibraryItem, String> itemCodeColumn;
#FXML
private TableColumn<LibraryItem, String> availableColumn;
#FXML
private TableColumn<LibraryItem, String> titleColumn;
#FXML
private TableColumn<LibraryItem, String> authorDirectorColumn;
private LibraryService libraryService = new LibraryService();
#Override
public void initialize(URL location, ResourceBundle resources) {
initializeTableView();
}
private void initializeTableView() {
List<LibraryItem> libraryItems = libraryService.getLibraryItems();
itemCodeColumn.setCellValueFactory(new PropertyValueFactory<>("itemCode"));
availableColumn.setCellValueFactory(new PropertyValueFactory<>("availability"));
titleColumn.setCellValueFactory(new PropertyValueFactory<>("title"));
// implement here check for each new row
if (checkIfBook(row))
authorDirectorColumn.setCellValueFactory(new PropertyValueFactory<>("author"));
else
authorDirectorColumn.setCellValueFactory(new PropertyValueFactory<>("director"));
//
libraryItemsTable.getItems().addAll(libraryItems);
}
If you follow the advice here and avoid the use of PropertyValueFactory, the solution becomes reasonably clear:
titleColumn.setCellValueFactory(data ->
new SimpleStringProperty(data.getValue().getTitle()));
authorDirectorColumn.setCellValueFactory(data -> {
LibraryItem item = data.getValue();
if (item instanceof Book book) {
return new SimpleStringProperty(book.getAuthor());
} else if (item instanceof Movie movie) {
return new SimpleStringProperty(movie.getProducer());
} else {
return null ;
}
});
Here's a complete example (I simplified the model classes for brevity, but retained enough to demonstrate the point):
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.IOException;
public class HelloApplication extends Application {
#Override
public void start(Stage stage) throws IOException {
TableView<LibraryItem> table = new TableView<>();
TableColumn<LibraryItem, String> titleColumn = new TableColumn<>("Title");
TableColumn<LibraryItem, String> authorProducerColumn = new TableColumn<>("Author/Producer");
table.getColumns().add(titleColumn);
table.getColumns().add(authorProducerColumn);
titleColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getTitle()));
authorProducerColumn.setCellValueFactory(data -> {
LibraryItem item = data.getValue();
if (item instanceof Book book) {
return new SimpleStringProperty(book.getAuthor());
} else if (item instanceof Movie movie) {
return new SimpleStringProperty(movie.getProducer());
} else return null ;
});
for (int i = 1 ; i <= 10 ; i++) {
Book book = new Book("Book "+i, "Author "+i);
Movie movie = new Movie("Movie "+i, "Producer "+i);
table.getItems().addAll(book, movie);
}
BorderPane root = new BorderPane(table);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public class LibraryItem {
private String title ;
public LibraryItem(String title) {
this.title = title ;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public class Movie extends LibraryItem {
private String producer ;
public Movie(String title, String producer) {
super(title);
this.producer = producer ;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
}
public class Book extends LibraryItem {
private String author ;
public Book(String title, String author) {
super(title);
this.author = author ;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
public static void main(String[] args) {
launch();
}
}
I have the following code to create a TreeTableView with a CheckComboBox in one column.
public class TreeTableViewSample extends Application {
List<Employee> employees = Arrays.<Employee>asList(
new Employee("Ethan Williams", ""),
new Employee("Emma Jones", ""),
new Employee("Michael Brown", ""),
new Employee("Anna Black", ""),
new Employee("Rodger York", ""),
new Employee("Susan Collins", ""));
final TreeItem<Employee> root = new TreeItem<>(new Employee("Department", ""));
final TreeItem<Employee> root1 = new TreeItem<>(new Employee("Executive Department", ""));
final TreeItem<Employee> root2 = new TreeItem<>(new Employee("Sales Department", ""));
public static void main(String[] args) {
Application.launch(TreeTableViewSample.class, args);
}
#Override
public void start(Stage stage) {
root.setExpanded(true);
employees.stream().forEach((employee) -> {
root1.getChildren().add(new TreeItem<>(employee));
root2.getChildren().add(new TreeItem<>(employee));
});
root.getChildren().addAll(root1, root2);
stage.setTitle("Tree Table View Sample");
final Scene scene = new Scene(new Group(), 400, 400);
scene.setFill(Color.LIGHTGRAY);
Group sceneRoot = (Group) scene.getRoot();
TreeTableColumn<Employee, String> empColumn
= new TreeTableColumn<>("Employee");
empColumn.setPrefWidth(150);
empColumn.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<Employee, String> param)
-> new ReadOnlyStringWrapper(param.getValue().getValue().getName())
);
TreeTableColumn<Employee, String> emailColumn
= new TreeTableColumn<>("Email");
emailColumn.setPrefWidth(190);
emailColumn.setEditable(true);
emailColumn.setCellFactory((TreeTableColumn<Employee, String> p) -> new CheckComboCell());
emailColumn.setCellValueFactory(
(TreeTableColumn.CellDataFeatures<Employee, String> param)
-> new ReadOnlyStringWrapper(param.getValue().getValue().getEmail())
);
TreeTableView<Employee> treeTableView = new TreeTableView<>(root);
treeTableView.setEditable(true);
treeTableView.getColumns().setAll(empColumn, emailColumn);
sceneRoot.getChildren().add(treeTableView);
stage.setScene(scene);
stage.show();
}
public class Employee {
private SimpleStringProperty name;
private SimpleStringProperty email;
public SimpleStringProperty nameProperty() {
if (name == null) {
name = new SimpleStringProperty(this, "name");
}
return name;
}
public SimpleStringProperty emailProperty() {
if (email == null) {
email = new SimpleStringProperty(this, "email");
}
return email;
}
private Employee(String name, String email) {
this.name = new SimpleStringProperty(name);
this.email = new SimpleStringProperty(email);
}
public String getName() {
return name.get();
}
public void setName(String fName) {
name.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
}
}
Cell Factory Class
public class CheckComboCell extends TreeTableCell<TreeTableViewSample.Employee, String> {
private final ComboBox<CheckComboCellModel> cb = new ComboBox<CheckComboCellModel>() {
#SuppressWarnings("restriction")
#Override
protected javafx.scene.control.Skin<?> createDefaultSkin() {
return new ComboBoxListViewSkin<CheckComboCellModel>(this) {
#Override
protected boolean isHideOnClickEnabled() {
return false;
}
};
}
};
private final ObservableList<CheckComboCellModel> items = FXCollections.observableArrayList();
private final Tooltip tooltip = new Tooltip();
public CheckComboCell() {
super();
populateAllocationType();
cb.setItems(items);
cb.setCellFactory((ListView<CheckComboCellModel> p) -> new ListCell<CheckComboCellModel>() {
private final CheckBox checkBox = new CheckBox();
private BooleanProperty booleanProperty;
{
checkBox.setOnAction(e -> getListView().getSelectionModel().select(getItem()));
}
#Override
protected void updateItem(CheckComboCellModel item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
checkBox.setText(item.toString());
if (booleanProperty != null) {
checkBox.selectedProperty().unbindBidirectional(booleanProperty);
}
booleanProperty = item.checkProperty();
checkBox.selectedProperty().bindBidirectional(booleanProperty);
setGraphic(checkBox);
} else {
setGraphic(null);
setText(null);
}
}
});
cb.setButtonCell(new ListCell<CheckComboCellModel>() {
#Override
protected void updateItem(CheckComboCellModel item, boolean empty) {
super.updateItem(item, empty);
String selected = cb.getItems().stream().filter(i -> i.getCheck())
.map(i -> i + "").collect(Collectors.joining(","));
setText(selected);
}
});
setGraphic(null);
}
private void populateAllocationType() {
items.add(new CheckComboCellModel("mail_1"));
items.add(new CheckComboCellModel("mail_2"));
items.add(new CheckComboCellModel("mail_3"));
items.add(new CheckComboCellModel("mail_4"));
items.add(new CheckComboCellModel("mail_5"));
}
#Override
public void startEdit() {
if (!isEditable() || !getTreeTableView().isEditable() || !getTableColumn().isEditable()) {
return;
}
super.startEdit();
setGraphic(cb);
}
#Override
public void commitEdit(String value) {
super.commitEdit(value);
setGraphic(null);
setText(cb.getButtonCell().getText());
}
#Override
public void cancelEdit() {
super.cancelEdit();
setGraphic(null);
setText(cb.getButtonCell().getText());
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setText(this.cb.getButtonCell().getText());
setGraphic(null);
}
}
}
Model class
public class CheckComboCellModel {
private final BooleanProperty check = new SimpleBooleanProperty(false);
private final StringProperty item = new SimpleStringProperty();
public CheckComboCellModel() {
}
public CheckComboCellModel(String item) {
this.item.set(item);
}
public CheckComboCellModel(String item, Boolean check) {
this.item.set(item);
this.check.set(check);
}
public BooleanProperty checkProperty() {
return check;
}
public Boolean getCheck() {
return check.getValue();
}
public void setCheck(Boolean value) {
check.set(value);
}
public StringProperty itemProperty() {
return item;
}
public String getItem() {
return item.getValueSafe();
}
public void setItem(String value) {
item.setValue(value);
}
#Override
public String toString() {
return item.getValue();
}
}
With this i get what i expect (i.e) a Column with CheckComboBox. But the issue is:
The application looks like this:
I selected some values
The values are updated in cell
But when the node is minimized
The updated value is displayed in next node. What i am doing wrong ? How can i solve this?
I have have implementaed a plugin project and want to use TestNG tab for runner purpose in this application. I have a solution for JUnit but in TestNG still I am stuck. Please help out from this situation. Kindly find the JUnit configuration tab code in below:
public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
new JUnitLaunchConfigurationTab(),
new JavaArgumentsTab(),
new JavaClasspathTab(),
new JavaJRETab(),
new SourceLookupTab(),
new EnvironmentTab(),
new CommonTab()
};
setTabs(tabs);
}
Please suggest.
****First create TestTab.java class by extend AbstractLaunchConfigurationTab******
private ILaunchConfigurationDialog fLaunchConfigurationDialog;
private final TestNGMainTab testngLaunchTab;
private Button runInUIThread;
/**
* Constructor to create a new junit test tab
*/
public TestTab() {
this.testngLaunchTab = new TestNGMainTab();
}
public void createControl(Composite parent) {
testngLaunchTab.createControl(parent);
Composite composite = (Composite) getControl();
createSpacer(composite);
createRunInUIThreadGroup(composite);
}
private void createRunInUIThreadGroup(Composite comp) {
runInUIThread = new Button(comp, SWT.CHECK);
runInUIThread.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
updateLaunchConfigurationDialog();
}
});
runInUIThread.setText(PDEUIMessages.PDEJUnitLaunchConfigurationTab_Run_Tests_In_UI_Thread);
GridDataFactory.fillDefaults().span(2, 0).grab(true, false).applyTo(runInUIThread);
}
private void createSpacer(Composite comp) {
Label label = new Label(comp, SWT.NONE);
GridDataFactory.fillDefaults().span(3, 0).applyTo(label);
}
public void initializeFrom(ILaunchConfiguration config) {
testngLaunchTab.initializeFrom(config);
updateRunInUIThreadGroup(config);
}
private void updateRunInUIThreadGroup(ILaunchConfiguration config) {
boolean shouldRunInUIThread = true;
try {
shouldRunInUIThread = config.getAttribute(IPDELauncherConstants.RUN_IN_UI_THREAD, true);
} catch (CoreException ce) {
}
runInUIThread.setSelection(shouldRunInUIThread);
}
public void performApply(ILaunchConfigurationWorkingCopy config) {
testngLaunchTab.performApply(config);
boolean selection = runInUIThread.getSelection();
config.setAttribute(IPDELauncherConstants.RUN_IN_UI_THREAD, selection);
}
#Override
public String getId() {
return IPDELauncherConstants.TAB_TEST_ID;
}
#Override
public void activated(ILaunchConfigurationWorkingCopy workingCopy) {
testngLaunchTab.activated(workingCopy);
}
#Override
public boolean canSave() {
return testngLaunchTab.canSave();
}
#Override
public void deactivated(ILaunchConfigurationWorkingCopy workingCopy) {
testngLaunchTab.deactivated(workingCopy);
}
#Override
public void dispose() {
testngLaunchTab.dispose();
}
#Override
public String getErrorMessage() {
return testngLaunchTab.getErrorMessage();
}
#Override
public Image getImage() {
return testngLaunchTab.getImage();
}
#Override
public String getMessage() {
return testngLaunchTab.getMessage();
}
public String getName() {
return testngLaunchTab.getName();
}
#Override
public boolean isValid(ILaunchConfiguration config) {
return testngLaunchTab.isValid(config);
}
public void setDefaults(ILaunchConfigurationWorkingCopy config) {
testngLaunchTab.setDefaults(config);
}
#Override
public void setLaunchConfigurationDialog(ILaunchConfigurationDialog dialog) {
testngLaunchTab.setLaunchConfigurationDialog(dialog);
this.fLaunchConfigurationDialog = dialog;
}
*** create Interface ITestNGPluginLauncherConstants*****
public interface ITestNGPluginLauncherConstants {
String LEGACY_UI_TEST_APPLICATION =
"org.testng.eclipse.runtime.legacytestapplication";
String NON_UI_THREAD_APPLICATION =
"org.testng.eclipse.runtime.nonuithreadtestapplication";
String UI_TEST_APPLICATION =
"org.testng.eclipse.runtime.uitestapplication";
String CORE_TEST_APPLICATION =
"org.testng.eclipse.runtime.coretestapplication";
String TestNGProgramBlock_headless = "No application [Headless]";
String TAB_PLUGIN_TESTNG_MAIN_ID =
"org.testng.eclipse.plugin.launch.tab.main";
}
****create class PluginTestNGMainTab.java*****
public class TestNGPluginTabGroup extends
AbstractLaunchConfigurationTabGroup {
public TestNGPluginTabGroup() {
}
public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
new TestTab(),
new PluginTestNGMainTab(),
new JavaArgumentsTab(),
new PluginsTab(false),
new JavaArgumentsTab(),
new PluginsTab(),
new TracingTab(),
new ConfigurationTab(true),
new TracingTab(),
new EnvironmentTab(),
new CommonTab()
};
setTabs(tabs);
}
}
**** create class TestNGProgramBlock.java extends ProgramBlock*****
public TestNGProgramBlock(AbstractLauncherTab tab) {
super(tab);
}
public void setDefaults(ILaunchConfigurationWorkingCopy config) {
if (!LauncherUtils.requiresUI(config))
config.setAttribute(IPDELauncherConstants.APPLICATION,
ITestNGPluginLauncherConstants.CORE_TEST_APPLICATION);
else
super.setDefaults(config);
}
protected String[] getApplicationNames() {
TreeSet result = new TreeSet();
result.add(ITestNGPluginLauncherConstants.TestNGProgramBlock_headless);
String[] appNames = super.getApplicationNames();
for (int i = 0; i < appNames.length; i++) {
result.add(appNames[i]);
}
return appNames;
}
protected void initializeApplicationSection(ILaunchConfiguration config)
throws CoreException {
String application =
config.getAttribute(IPDELauncherConstants.APPLICATION, (String)null);
if(ITestNGPluginLauncherConstants.CORE_TEST_APPLICATION.
equals(application))
fApplicationCombo.setText(ITestNGPluginLauncherConstants.
TestNGProgramBlock_headless);
else
super.initializeApplicationSection(config);
}
protected void saveApplicationSection(ILaunchConfigurationWorkingCopy config)
{
if(fApplicationCombo.getText().equals(ITestNGPluginLauncherConstants.
TestNGPogramBlock_headless)){
String appName = fApplicationCombo.isEnabled() ?
ITestNGPluginLauncherConstants.CORE_TEST_APPLICATION : null;
config.setAttribute(IPDELauncherConstants.APPLICATION, appName);
config.setAttribute(IPDELauncherConstants.APP_TO_TEST, (String)null);
}
}
}
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.... :)
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());