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
Related
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();
}
}
My problem is simple but I have no clue how to solve it. I have a feedbackPanel and I want to show an error message if the BootstrapDownloadLink fails. With a submit I could easily do:
protected void onSubmit(AjaxRequestTarget target) {
...
error("File_not_found"); //Wicket will print this on the feedback panel
target.add(getModalPanel().getFeedbackPanel()); //But i need to refresh it first
}
But the button is inside a panel which I fill with a populateItem and is the only way I know to insert Bootstrap Styles to it. The code of the button:
BootstrapDownloadLink downloadDocument = new BootstrapDownloadLink(IDITEMREPEATER, file) {
#Override
public void onClick() {
File file = (File)getModelObject();
if(file.exists()) {
IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream, file.getName()));
} else {
error(getString("error_fichero_no_existe"));
/// ???? need to refresh-> getModalPanel().getFeedbackPanel()
}
}
};
downloadDocument.setIconType(GlyphIconType.clouddownload);
downloadDocument.add(new AttributeModifier("title", getString("documentos.descargar")));
downloadDocument.add(new AttributeModifier("class", " btn btn-info negrita btn-xs center-block"));
downloadDocument.setVisible(Boolean.TRUE);
list.add(downloadDocument);
You could create or extend from an AjaxDownloadLink, for example like here.
The main idea is to have an AjaxBehavior that does the download, and you get a public void onClick(AjaxRequestTarget target) in which you can add the FeedbackPanel
downloadBehavior = new AbstractAjaxBehavior()
{
private static final long serialVersionUID = 3472918725573624819L;
#Override
public void onRequest()
{
[...]
ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(
AjaxDownloadLink.this.getModelObject(), name);
handler.setContentDisposition(ContentDisposition.ATTACHMENT);
getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
}
};
And use that behavior in the onclick:
#Override
public void onClick(AjaxRequestTarget aTarget)
{
String url = downloadBehavior.getCallbackUrl().toString();
if (addAntiCache) {
url = url + (url.contains("?") ? "&" : "?");
url = url + "antiCache=" + System.currentTimeMillis();
}
// the timeout is needed to let Wicket release the channel
aTarget.appendJavaScript("setTimeout(\"window.location.href='" + url + "'\", 100);");
}
You can use target.addChildren(getPage(), IFeedback.class). This will add all instances of IFeedback interface in the page to the AjaxRequestTarget.
You can also use FeedbackPanel.class instead of the interface.
Or use getPage().visit(new IVisitor() {...}) to find a specific feedback panel if you don't want to add others which are not related.
I am developing a GWT app where I am using paging toolbar. When I have more than 10 groups in grid, user can go to second page with paging toolbar. But when I press button to go to the second page, it goes to that second, loading is shown but then toolbar is back to the first page with those first. 10 items.
This is first page:
And when I press button for second page I get this loading:
But then after that toolbar backs me to the first page. This is my class for paging toolbar:
public class MyPagingToolBar extends PagingToolBar {
private static final ConsoleMessages MSGS = GWT.create(ConsoleMessages.class);
public MyPagingToolBar(int pageSize) {
super(pageSize);
PagingToolBarMessages pagingToolbarMessages = getMessages();
pagingToolbarMessages.setBeforePageText(MSGS.pagingToolbarPage());
pagingToolbarMessages.setAfterPageText(MSGS.pagingToolbarOf().concat("{0}"));
StringBuilder sb = new StringBuilder();
sb.append(MSGS.pagingToolbarShowingPre())
.append(" {0} - {1} ")
.append(MSGS.pagingToolbarShowingMid())
.append(" {2} ")
.append(MSGS.pagingToolbarShowingPost());
pagingToolbarMessages.setDisplayMsg(sb.toString());
pagingToolbarMessages.setEmptyMsg(MSGS.pagingToolbarNoResult());
pagingToolbarMessages.setFirstText(MSGS.pagingToolbarFirstPage());
pagingToolbarMessages.setPrevText(MSGS.pagingToolbarPrevPage());
pagingToolbarMessages.setNextText(MSGS.pagingToolbarNextPage());
pagingToolbarMessages.setLastText(MSGS.pagingToolbarLastPage());
pagingToolbarMessages.setRefreshText(MSGS.pagingToolbarRefresh());
}
}
And this is class where I using MyPagingToolbar:
public abstract class EntityGrid<M extends GwtEntityModel> extends ContentPanel {
private static final ConsoleMessages MSGS = GWT.create(ConsoleMessages.class);
private static final int ENTITY_PAGE_SIZE = 10;
protected GwtSession currentSession;
private AbstractEntityView<M> parentEntityView;
private EntityCRUDToolbar<M> entityCRUDToolbar;
protected KapuaGrid<M> entityGrid;
protected BasePagingLoader<PagingLoadResult<M>> entityLoader;
protected ListStore<M> entityStore;
protected PagingToolBar entityPagingToolbar;
protected EntityFilterPanel<M> filterPanel;
protected EntityGrid(AbstractEntityView<M> entityView, GwtSession currentSession) {
super(new FitLayout());
//
// Set other properties
this.parentEntityView = entityView;
this.currentSession = currentSession;
//
// Container borders
setBorders(false);
setBodyBorder(true);
setHeaderVisible(false);
//
// CRUD toolbar
entityCRUDToolbar = getToolbar();
if (entityCRUDToolbar != null) {
setTopComponent(entityCRUDToolbar);
}
//
// Paging toolbar
entityPagingToolbar = getPagingToolbar();
if (entityPagingToolbar != null) {
setBottomComponent(entityPagingToolbar);
}
}
#Override
protected void onRender(Element target, int index) {
super.onRender(target, index);
//
// Configure Entity Grid
// Data Proxy
RpcProxy<PagingLoadResult<M>> dataProxy = getDataProxy();
// Data Loader
entityLoader = new BasePagingLoader<PagingLoadResult<M>>(dataProxy);
// Data Store
entityStore = new ListStore<M>(entityLoader);
//
// Grid Data Load Listener
entityLoader.addLoadListener(new EntityGridLoadListener<M>(this, entityStore));
//
// Bind Entity Paging Toolbar
if (entityPagingToolbar != null) {
entityPagingToolbar.bind(entityLoader);
}
//
// Configure columns
ColumnModel columnModel = new ColumnModel(getColumns());
//
// Set grid
entityGrid = new KapuaGrid<M>(entityStore, columnModel);
add(entityGrid);
//
// Bind the grid to CRUD toolbar
entityCRUDToolbar.setEntityGrid(this);
//
// Grid selection mode
GridSelectionModel<M> selectionModel = entityGrid.getSelectionModel();
selectionModel.setSelectionMode(SelectionMode.SINGLE);
selectionModel.addSelectionChangedListener(new SelectionChangedListener<M>() {
#Override
public void selectionChanged(SelectionChangedEvent<M> se) {
selectionChangedEvent(se.getSelectedItem());
}
});
//
// Grid view options
GridView gridView = entityGrid.getView();
gridView.setEmptyText(MSGS.gridEmptyResult());
//
// Do first load
refresh();
}
protected EntityCRUDToolbar<M> getToolbar() {
return new EntityCRUDToolbar<M>(currentSession);
}
protected abstract RpcProxy<PagingLoadResult<M>> getDataProxy();
protected PagingToolBar getPagingToolbar() {
return new MyPagingToolBar(ENTITY_PAGE_SIZE);
}
protected abstract List<ColumnConfig> getColumns();
public void refresh() {
entityLoader.load();
entityPagingToolbar.enable();
}
public void refresh(GwtQuery query) {
// m_filterPredicates = predicates;
setFilterQuery(query);
entityLoader.load();
entityPagingToolbar.enable();
}
public void setFilterPanel(EntityFilterPanel<M> filterPanel) {
this.filterPanel = filterPanel;
entityCRUDToolbar.setFilterPanel(filterPanel);
}
protected void selectionChangedEvent(M selectedItem) {
if (parentEntityView != null) {
parentEntityView.setSelectedEntity(selectedItem);
}
}
public void setPagingToolbar(PagingToolBar entityPagingToolbar) {
this.entityPagingToolbar = entityPagingToolbar;
}
public GridSelectionModel<M> getSelectionModel() {
return entityGrid.getSelectionModel();
}
protected abstract GwtQuery getFilterQuery();
protected abstract void setFilterQuery(GwtQuery filterQuery);
What is my mistake?
EDIT: This is my server method:
int totalLength = 0;
List<GwtGroup> gwtGroupList = new ArrayList<GwtGroup>();
try {
KapuaLocator locator = KapuaLocator.getInstance();
GroupService groupService = locator.getService(GroupService.class);
UserService userService = locator.getService(UserService.class);
GroupQuery groupQuery = GwtKapuaAuthorizationModelConverter.convertGroupQuery(loadConfig,
gwtGroupQuery);
GroupListResult groups = groupService.query(groupQuery);
if (!groups.isEmpty()) {
if (groups.getSize() >= loadConfig.getLimit()) {
totalLength = Long.valueOf(groupService.count(groupQuery)).intValue();
} else {
totalLength = groups.getSize();
}
for (Group g : groups.getItems()) {
gwtGroupList.add(KapuaGwtAuthorizationModelConverter.convertGroup(g));
for (GwtGroup gwtGroup : gwtGroupList) {
User user = userService.find(g.getScopeId(), g.getCreatedBy());
if (user != null) {
gwtGroup.setUserName(user.getDisplayName());
}
}
}
}
} catch (Exception e) {
KapuaExceptionHandler.handle(e);
}
return new BasePagingLoadResult<GwtGroup>(gwtGroupList, loadConfig.getOffset(),
totalLength);
}
(Didn't I just answer this an earlier version of this? Please don't delete questions after you get an answer to them, or people won't answer your questions at all any more.)
If the server is given a request for the second page (offset of 10), but returns a PagingLoadResult for the first page anyway, that is what you will see. Make sure your server is actually sending back the second page - not only that, but it must send in the response object the offset that it actually used for the next page (in your example, 10), or else the paging toolbar will not know which page the user is actually on.
Make sure the server is taking the request offset into account, and returning the parameters it used correctly to the client. If that appears to be correct, please add the server method to your question, and add logging on the client and server to verify what is being requested, vs what is being returned.
Skipping items in Java is pretty straightforward, but will not scale very well for huge lists.
In short, just skip the first offset items when looping.
First though, a free code review - this is very inefficient code - you are rewriting every item in gwtGroupList every time you add something:
for (Group g : groups.getItems()) {
gwtGroupList.add(KapuaGwtAuthorizationModelConverter.convertGroup(g));
for (GwtGroup gwtGroup : gwtGroupList) {
User user = userService.find(g.getScopeId(), g.getCreatedBy());
if (user != null) {
gwtGroup.setUserName(user.getDisplayName());
}
}
It could instead read:
for (Group g : groups.getItems()) {
gwtGroupList.add(KapuaGwtAuthorizationModelConverter.convertGroup(g));
}
for (GwtGroup gwtGroup : gwtGroupList) {
User user = userService.find(g.getScopeId(), g.getCreatedBy());
if (user != null) {
gwtGroup.setUserName(user.getDisplayName());
}
}
Alternatively, they could be just one loop.
Now we modify it again, to handle offset and limit:
int itemsLeftToSkip = offset;
for (Group g : groups.getItems()) {
if (itemsLeftToSkip > 0) {
itemsLeftToSkip--;
continue;//we skipped this item, and now the count is one less
}
if (gwtGroupList.size() >= limit) {
break;//we've got enough already, quit the loop
}
gwtGroupList.add(KapuaGwtAuthorizationModelConverter.convertGroup(g));
}
for (GwtGroup gwtGroup : gwtGroupList) {
User user = userService.find(g.getScopeId(), g.getCreatedBy());
if (user != null) {
gwtGroup.setUserName(user.getDisplayName());
}
}
Notice how we use offset to avoid items until we get to the ones that are needed for the new page, and we use limit to only send that many time, at a maximum.
Finally, unless your groupQuery already has a limit built in (in which case, you should put the offset there too...), the if (groups.getSize() >= loadConfig.getLimit()) { block of code is likely not necessary at all, since you've already loaded all items. If it is necessary because there is a limit, then your pages will not correctly load all the way to the end. Either way, investigate this code, and possibly get it reviewed further, something looks very wrong there.
My problem is that after closing the frame for admin that will set the available products the selected products gets unselected
The checkbox here must get activated by the admin from the other form
Here's my code:
private void chk1ActionPerformed(java.awt.event.ActionEvent evt) {
Cashier x = new Cashier();
if (chk1.isSelected() == true)
{
x.chkpr1.setEnabled(true);
}
else
{
x.chkpr1.setEnabled(false);
}
}
it's as it says on the title
First of all, I would like to apologize if this is a dumb question =[
so basically i'm trying to send email through gwt. I have no idea how gwt mail work so instead I tried to use php way (which is more familiar to me) but I have no idea how to get this working.
So.. in my war folder I have my index.html and email.php that I've created. In my index.html, I have a form that calls my email.php.
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "did you make sure to fill everything?";
return false;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email\n\n Message:\n$message";
$headers = "From: noreply#somedomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
above is my php code that I am currently using. However not only eclipse does not recognize php but also when I press my button, it only prints out this code and not running it.
Does this happen to anyone and can anyone please help me?
Thank you =]
What you can do:
Recreate the email form in GWT with FormPanel, or
create your own POST-Request in GWT with RequestBuilder
In both cases: the 'echo' statements that your PHP form returns will not be appended to the HTML page but returned to you as a String. You will have to decide what to do (tell the user? take other action) in your GWT code.
Recreate as form panel:
// create the textboxes of the form with their proper form names
TextBox tbName = new TextBox();
tbName.setName( "name" );
TextBox tbEmail = new TextBox();
tbEmail.setName( "email" );
TextBox tbMessage = new TextBox();
tbMessage.setName( "message" );
// create the form panel
final FormPanel emailFormPanel = new FormPanel();
// TODO: add the form panel to some kind of parent widget / ui object
emailFormPanel.setAction( "/contextRoot/path/to/email.php" );
emailFormPanel.setMethod( "POST" );
// add the textboxes to the form panel
emailFormPanel.add( tbName );
emailFormPanel.add( tbEmail );
emailFormPanel.add( tbMessage );
// create the form submit button
Button btnSubmit = new Button( "Submit", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
emailFormPanel.submit();
}
} );
// create the formpanel handler for a successful submit
// any error message ("did you forget to ...") will be returned here
emailFormPanel.addSubmitCompleteHandler( new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String errorString = event.getResults();
// TODO: decide what to do with a potential non-empty string
}
} );
Create your own POST-Request with RequestBuilder:
// create the textboxes of the form with their proper form names
final TextBox tbName = new TextBox();
final TextBox tbEmail = new TextBox();
final TextBox tbMessage = new TextBox();
// create the form submit button
Button btnSubmit = new Button( "Submit", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
submitEmailFormRequestBuilder( tbName, tbEmail, tbMessage );
}
} );
// TODO: add textboxes and Submit-Button to the DOM-tree
submit the textbox values:
protected void submitEmailFormRequestBuilder(TextBox name, TextBox email, TextBox message) {
// create the request content in a way that the php script can read it:
// for every textbox the php textbox-name = user-value
StringBuilder requestData = new StringBuilder();
requestData.append( "name=" + name.getValue() );
requestData.append( "&email=" + email.getValue() );
requestData.append( "&message=" + message.getValue() );
// create the REST request callback
RequestCallback callback = new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
String errorMessage = response.getText();
// TODO: handle potential error-message
}
#Override
public void onError(Request request, Throwable exception) {
// TODO: handle timeouts and other sending failures like cross-domain posting
}
};
// create the REST request as POST request
RequestBuilder build = new RequestBuilder( RequestBuilder.POST, "/contextRoot/email.php" );
try {
build.sendRequest( requestData.toString(), callback );
}
catch (RequestException e) {
// handle exception
}
}
Otherwise, if index.html is not your GWT starting page where the .nocache.js module is called, then you could include it in your GWT code with an IFrame.