how to get the selected items in DualListField? - java

i don't have any idea on how to get the selected items in a DualListField. Can somebody help me. so here's my code on DualListField. And I want txtCat to be the container of the selected items aside from the TextCell. And also I want the selected item to be converted on its IDCategory
final DualListField<Category, String> field = new DualListField<Category, String>(category, toCategory, catProp.strName(), txCell);
field.addValidator(new EmptyValidator<List<Category>>());
field.setEnableDnd(true);
field.setMode(Mode.INSERT);
vlc.add(new FieldLabel(field, "Categories"), new VerticalLayoutData(1, -1, new Margins(10)));
txtCat = new TextField();
txtCat.setEmptyText("Value");
txtCat.addFocusHandler(new FocusEvent.FocusHandler() {
#Override
public void onFocus(FocusEvent event) {
field.getFromStore();
}
});
vlc.add(new FieldLabel(txtCat, "Chosen Categories"), new VerticalLayoutData(-18, -1, new Margins(10)));

In latest GXT3 version DualListField, You could get the selected items in ToView part through field.getValue() method. You get all the data in ToView as follows. field.getToView().getStore().getAll() . hth

Related

Vaadin 14 LTS Grid refresh after adding new data not working

I'm trying to refresh grid after adding an row into it, but it's not working. Here is my Event Listener on my UI Code : Edited Full code.
Grid<TransactionModel> transactionData = new Grid<>(TransactionModel.class);
try {
// transactionData.setItems(transactionServices.getTransactionTable());
List<TransactionModel> transactionList = transactionServices.getTransactionTable();
ListDataProvider<TransactionModel> transactionDataProvider = new ListDataProvider<>(transactionList);
transactionData.setDataProvider(transactionDataProvider);
transactionData.setColumns("id", "transactionTimestamp", "srcAccountId", "dstAccountId", "amount");
Grid.Column<TransactionModel> idColumn = transactionData.getColumnByKey("id");
Grid.Column<TransactionModel> srcAccountIdColumn = transactionData.getColumnByKey("srcAccountId");
Grid.Column<TransactionModel> dstAccountIdColumn = transactionData.getColumnByKey("dstAccountId");
HeaderRow filterRow2 = transactionData.appendHeaderRow();
TransactionFilterModel transactionFilterModel = new TransactionFilterModel();
transactionDataProvider.setFilter(transaction -> transactionFilterModel.find(transaction));
// Filter srcAccountId
TextField idField = new TextField();
idField.addValueChangeListener(event -> {
transactionFilterModel.setId(event.getValue());
transactionDataProvider.refreshAll();
});
idField.setValueChangeMode(ValueChangeMode.EAGER);
filterRow2.getCell(idColumn).setComponent(idField);
idField.setSizeFull();
idField.getElement().setAttribute("focus-terget", "");
// Filter srcAccountId
TextField srcAccountIdField = new TextField();
srcAccountIdField.addValueChangeListener(event -> {
transactionFilterModel.setSrcAccountId(event.getValue());
transactionDataProvider.refreshAll();
});
srcAccountIdField.setValueChangeMode(ValueChangeMode.EAGER);
filterRow2.getCell(srcAccountIdColumn).setComponent(srcAccountIdField);
srcAccountIdField.setSizeFull();
srcAccountIdField.getElement().setAttribute("focus-terget", "");
// Filter dstAccountId
TextField dstAccountIdField = new TextField();
dstAccountIdField.addValueChangeListener(event -> {
transactionFilterModel.setDstAccountId(event.getValue());
transactionDataProvider.refreshAll();
});
dstAccountIdField.setValueChangeMode(ValueChangeMode.EAGER);
filterRow2.getCell(dstAccountIdColumn).setComponent(dstAccountIdField);
dstAccountIdField.setSizeFull();
dstAccountIdField.getElement().setAttribute("focus-terget", "");
transactionData.setWidth("50%");
} catch (JsonProcessingException | EndpointException ex) {
Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ex);
}
// Event Listener
submitButton.addClickListener(e -> {
System.out.println("Submitted !");
AccountModel submittedModel = new AccountModel();
if (accountModelBinder.writeBeanIfValid(submittedModel)) {
try {
accountServices.registerAccount(submittedModel);
accountIdTextField.clear();
nameTextField.clear();
addressTextField.clear();
birthDateDatePicker.clear();
allowNegativeBalanceButtonGroup.clear();
} catch (EndpointException | JsonProcessingException ez) {
Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ez);
}
}
accountData.getDataProvider().refreshAll(); // <- REFRESH
});
And for service I'm using rest, here is the accountservice code:
public List<AccountModel> getAccountTable() throws JsonProcessingException, EndpointException {
List<AccountModel> datalog = new JsonResponseReader(restMockvaEndpoint.send(new EndpointRequestBuilder()
.method("GET")
.resource("/account")
.build()
)).getContentTable(AccountModel.class).getData();
return datalog;
}
public AccountModel registerAccount(AccountModel accountModel) throws JsonProcessingException, EndpointException{
AccountModel account = new JsonResponseReader(restMockvaEndpoint.send(new EndpointRequestBuilder()
.method("POST")
.content(Json.getWriter().writeValueAsBytes(accountModel), MediaType.APPLICATION_JSON)
.resource("/account")
.build())).getContentObject(AccountModel.class);
return account;
}
Edited : Add registerAccount.
The problem is when I click submitButton for adding new data, the grid doesn't refresh. Any ideas?
For this to work with a ListDataProvider, you would have to modify the underlying list (add/remove items).
Now that you call refreshAll(), it just reads the list you passed again, and as it still contains the same items, nothing changes. It does not know to fetch the items from your service again.
There are a few solutions that I can think of:
1. Manually add the new item to the list (it will then appear at the end of the grid):
accountList.add(submittedModel);
...
// This instructs the grid to read the list again
accountData.getDataProvider().refreshAll();
If your accountServices.registerAccount method returns the newly saved item, you might want to add that one instead.
2. Set the items again
You could fetch the items again and set a new data provider. You can just use setItems(...) then, which uses a ListDataProvider under the hood.
// Run this both when first creating the grid, and again after the new item is saved.
// This time you don't need to call refreshAll()
List<AccountModel> accountList = accountServices.getAccountTable();
accountData.setItems(accountList);
3. Use a lazy data provider
When you use a lazy data provider, for example from callbacks, then calling refreshAll() executes those callbacks again to fetch new items.
In this case you need to implement the needed service methods, and it requires a bit more work if you need sorting or filtering.
this.setDataProvider(DataProvider.fromCallbacks(
query -> myAccountService.getAccounts(query.getOffset(), query.getLimit()).stream(),
query -> myAccountService.countAccounts()
));

Arrow key selection does not work to Autocompleated combo box when combo box values are reload java Fx

The 1st time program is loaded the arrow key selection in autocomplete combobox works. But after I clear and reload the values in it using a method below the arrow key navigation and selection of combobox items does not work.
I use TextFields.bindAutoCompletion method from ControlsFx 8 to bind combobox.
// load Auto Compleat nic,fname,lname,id values for search Combo Box
private void loadValuesToComboSearchBox() {
try {
// clear elements of Search Combo Box
comboSearch.getItems().clear();
// Disable Search Combo Box
comboSearch.setEditable(false);
// load Auto Compleat nic,fname,lname,id values for search Text Field
ResultSet getsearchElements = employeDao.getSearchemployeeByNicFnameLnmeId();
LinkedHashSet<String> addElements = new LinkedHashSet<>();
while (getsearchElements.next()) {
addElements.add(getsearchElements.getString("id"));
addElements.add(getsearchElements.getString("firstname"));
addElements.add(getsearchElements.getString("lastname"));
addElements.add(getsearchElements.getString("nic"));
}
// Add elements to Auto Compleat Text Field
TextFields.bindAutoCompletion(comboSearch.getEditor(), addElements);
// Enable Search Combo Box
comboSearch.setEditable(true);
} catch (Exception e) {
new Alert(Alert.AlertType.INFORMATION, e + "", ButtonType.OK).showAndWait();
e.printStackTrace();
}
}
I believe this issue occurs due to the several overlapping AutoCompletionBindings.
In order to fix that you should keep reference to the previous binding and dispose it upon reload. Also, note that to clear the selection in JavaFX combobox more steps should be performed.
private AutoCompletionBinding<String> completion;
....
private void loadValuesToComboSearchBox() {
try {
// clear selection
comboSearch.getItems().clear();
comboSearch.valueProperty().set(null);
comboSearch.getEditor().clear();
comboSearch.setEditable(false);
ResultSet getSearchElements = employeDao.getSearchemployeeByNicFnameLnmeId();
Set<String> addElements = new LinkedHashSet<>();
while (getSearchElements.next()) {
addElements.add(getSearchElements.getString("id"));
addElements.add(getSearchElements.getString("firstname"));
addElements.add(getSearchElements.getString("lastname"));
addElements.add(getSearchElements.getString("nic"));
}
if (completion != null) {
completion.dispose();
}
completion = TextFields.bindAutoCompletion(comboSearch.getEditor(), addElements);
comboSearch.setEditable(true);
} catch (Exception e) {
new Alert(Alert.AlertType.INFORMATION, e + "", ButtonType.OK).showAndWait();
e.printStackTrace();
}
}

ActionListener and combo-box issue

I'm currently having an issue where I am creating a simple web browser and want to write the url of each page visited. Anyway, when the History combo-box is being filled with the URL's the .addItem function is triggering my action listener. Is there any way around this?
Action Listener:
historyList.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
final String url= historyList.getSelectedItem().toString();
addressbar.setText(url); //set the address bar to the url
historyArray[historynum] = url; //add the url to the array which contains the history
historynum = historynum + 1; //move one up the history array
Display(url); //display the url
backplace = 1; //reset the amount of backs a user can take
forwardBtn = false; //not allow the user to go forward again
}
}
);
}
adding URL's from config file to combo:
for (String linehistory : Files.readAllLines(Paths.get("config.history"),Charset.defaultCharset())) {
if (!(linehistory ==null)){
for (String partHistory : linehistory.split("\\s+")) {
String historylines = partHistory;
if( i >6){
if (!(partHistory ==null)){
historyList.addItem(partHistory);
}
}
i = i +1;
}
}
I have noticed this, and I think it may be due to the state of the combo-box being changed, is there a way to change this to onClick? http://imgur.com/aTg9n2E

Retrieve TextField value from the ListView

I have ListView.Where iam showing the some records.The ListView contain Lable and TextField.I entered some data in the textField(which is in ListView).On Submit() method,i am trying to retrieve the entered textfield value.But i am not getting the value which i entered in textbox.Please let me know how to get the entered value from textfield?Below is my code.
public List<StockCountDetail> getItemEntryDetails() {
List<StockCountDetail> myStockCountDetailList = new ArrayList<StockCountDetail>();
List<StockKeepingUnit> mySkuList = MpoBeanFactory.getBean(StockKeepingUnitDAO.class).getByStockLocation(stockLocationModel.getObject());
myStockCountDetailList.clear();
for (StockKeepingUnit mySku : mySkuList) {
StockCountDetail stockCountDetail = new StockCountDetail();
stockCountDetail.setProduct(mySku.getProduct());
myStockCountDetailList.add(stockCountDetail);
}
return myStockCountDetailList;
}
myStockCountDetailList = new ListView<StockCountDetail>("itemList", new PropertyModel<List<StockCountDetail>>(
StockCountEditPage.this, "itemEntryDetails")) {
#Override
protected void populateItem(ListItem<StockCountDetail> aItem) {
aItem.add(new AttributeAppender("class", true, new Model<String>(aItem.getIndex() % 2 == 0 ? "even" : "odd"), " "));
aItem.add(new Label("product", aItem.getModelObject().getProduct().getCode()));
aItem.add(new Label("description", aItem.getModelObject().getProduct().getDescription()));
aItem.add(new CheckBox("skipFlag", new PropertyModel<Boolean>(aItem.getModel(), "skipFlag")));
aItem.add(new TextField<Integer>("count", new PropertyModel<Integer>(aItem.getModel(), "count")));
}
};
myStockCountDetailList.setReuseItems(true);
form.add(myStockCountDetailList);
setOutputMarkupId(true);
AjaxFallbackButton mySave = new AjaxFallbackButton("save", form) {
#Override
protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) {
saveStockCount();
aTarget.addComponent(feedbackPanel);
}
};
form.add(mySave);
private void saveStockCount() {
boolean recordAdded = false;
for (StockCountDetail myStockCount : myStockCountDetailList.getModelObject()) {
if (!myStockCount.isSkipFlag()) {
myStockTransaction.setQuantity(new BigDecimal(myStockCount.getCount()));
}
here i am not getting the value using myStockCount.getCount() which is the entered value of textbox in listview.let me know how to get value of textbox?
Your ListView uses a PropertyModel that gets its value from calling getItemEntryDetails().
It you call myStockCountDetailList.getModelObject() then the resulting object will come from this.getItemEntryDetails() which will return a new List with new StockCountDetails.
In order to retain the value, you could store the list in a field.

ExtGWT StoreFilterField input doesn't react

I'm trying to build grid with build in column filtering (using sencha gxt), here is my code:
public Grid<Stock> createGrid() {
// Columns definition
ColumnConfig<Stock, String> nameCol = new ColumnConfig<Stock, String>(props.name(), 100, "Company");
// Column model definition and creation
List<ColumnConfig<Stock, ?>> cl = new ArrayList<ColumnConfig<Stock, ?>>();
cl.add(nameCol);
ColumnModel<Stock> cm = new ColumnModel<Stock>(cl);
// Data populating
ListStore<Stock> store = new ListStore<Stock>(props.key());
store.addAll(TestData.getStocks());
// Grid creation with data
final Grid<Stock> grid = new Grid<Stock>(store, cm);
grid.getView().setAutoExpandColumn(nameCol);
grid.setBorders(false);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
// Filters definition
StoreFilterField<Stock> filter = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock item, String filter) {
// Window.alert(String.valueOf("a"));
String name = item.getName();
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter.bind(store);
cm.addHeaderGroup(0, 0, new HeaderGroupConfig(filter, 1, 1));
filter.focus();
return grid;
}
My problem is: after I run this code, I cannot write anything to filter input, I'm using test data and classes (Stock.java and StockProperties.java) from this example: http://sencha.com/examples-dev/#ExamplePlace:filtergrid
I try to put allert in doSelect method to check if this function was called, but it wasn't.
Any idea will be welcome. Thanks.
I was able to make your code work. I observed that there were compiler errors in the code for StoreFilterField class. Here is the code that filters the grid based on the values in the first column, that is, name field in the Stock model.
StoreFilterField<Stock> filter1 = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock record, String property, String filter) {
String name = record.get("name");
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter1.bind(store);
Btw, I tested this with GXT 2.2.5 and GWT 2.4.
Thanks,
Ganesh
I solve this problem according to this paper http://www.sencha.com/forum/archive/index.php/ … but I replace disableTextSelection(false) with setAllowTextSelection(true);

Categories