Retrieving current user entered value from GWT SuggestBox - java

I'm new to GWT. I have a simple SuggestBox which is populated using a MultiWordSuggestOracle. Users input their data to this SuggestBox, and if they find any match with the existing Suggestions its well and good. I'm able to retrieve this value in the SelectionHandler code as below.
display.getSuggestBox().addSelectionHandler(new SelectionHandler<Suggestion>() {
public void onSelection(SelectionEvent<Suggestion> event) {
String selectedProperty = ((SuggestBox)event.getSource()).getValue();
// do something with the property value
}
});
But users are allowed to enter values which are not already in the Suggestion oracle, in which case I should read this value and do something with this,may be saving to db as a new data.(The thing which I'm looking for is something like a browsers navigation widget where we show suggestions, users can pick up any suggestion or he can type in his new entry and carry on.) What I needed is a way to retrieve this new text user has entered? Data will be read on a button click. What I tried out is this.
display.getSaveBtn().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String selectedProperty = display.getSuggestBox().getValue();
//String selectedProperty2 = display.getSuggestBox().getText();
// Blank in both cases :(
// tried display.getSuggestBox().getTextBox().getValue(),but blank again
}
});
I tried to employ onChange() event handlers (as shown below)
display.getSuggestBox().addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
String selectedProperty = ((SuggestBox)event.getSource()).getValue();
Window.alert("on change -- "+selectedProperty);
}
});
This is working fine except one scenario. Suppose there are two suggestions in the oracle,say 'createTicketWsdl' and 'createTicketTimeout'. When the user types in 'cr', he is opted with these two options, and if he selects 'createTicketWsdl' by pressing keyboard ENTER, then my alert is printing 'createTicketWsdl' which is correct. But if he selects 'createTicketWsdl' using mouse, then my alert is printing 'cr' (I tried to post the screenshot to give a better understanding, but being a new user I'm not allowed).(which I wanted to get as 'createTicketWsdl'since thats what he has selected). Soon after printing my alert, the value in the SuggestBox changes to 'createTicketWsdl'.
Is there a way to retrieve the value of the suggest box? I saw a similiar thread GWT SuggestBox + ListBox Widget, where some source code for a custom widget is available. But I didn't take the pain of trying out that, since what I want is simply get the current value from the SuggestBox and I hope there should be some easy way.
Thanks for all your help!

Your question is not very clear. You need to clarify your language a lil' bit. For example - is the following a question or an assertion? I mean, it sounds like an assertion but it has a question mark.
What I needed is a way to retrieve this new text user has entered?
Also, I do not understand what you mean by "he is opted by". Did you mean to say, "he is presented with the options ..." ?
Therefore, I am guessing your situation.
You have a listbox of existing items.
You have a textbox which allows freeform text entry
Any items whose prefix values matches the current textbox entry, the listbox items would be filtered to be limited to the matching items.
Even if the current textbox entry presents matching prefixes to filtering the listbox, the user can still perform freeform text entry. So, there are two possible cases here
4.1 the user clicks on the list box to select one of the filtered items
4.2 the user press enter key, which triggers selection of the current value of the textbox.
However, you find your widget participating in a race condition, so that when you click on the widget, the ValueChangeHandler gets triggered rather than the SelectionHandler. I do not know the structure of your widget so that is my best guess.
The problem is that you are allowing two separate modes of obtaining an outcome and you probably did not have well-defined state machine to handle choosing the appropriate mode. One mode is by the textbox and the other is by selection on the listbox - and you do not have a well-defined way of which would mode would be effective at any moment.
If my guess is accurate, this is what you need to do:
You must restrict your outcome to coming from only the textbox.
Your listbox selection must not trigger any outcome. Any change in listbox selection must propagate back to the textbox - to allow the user the chance of making further freeform entry based on that value.
only the keyboard enter on the textbox will trigger the final outcome.

Related

When i navigate to some field using tab and enter some text text getting disappeared?

I have a table of forms which accepts first name, last name etc. When I navigate through using the tab key and enter some text in first name, all of the text disappears and that row gets selected. I have tried almost all techniques.
Is there any way we can avoid that using coding?
If I use the mouse then it wont give that error.
Assuming an otherwise correct use of JTable, you may need to terminate the edit when focus is lost, as suggested here and here:
table.putClientProperty("terminateEditOnFocusLost", true);

String Tokenizer.nextElement for JComboBox

I'm using
int TxtAge = Integer.parseInt(tfAge.getText().trim());
to get value from my textfield and search it in database.
Then, I'm using Integer age = Integer.parseInt(stringTokenizer.nextElement().toString()); to go to next attributes in my database.
I have no problem using those codes for textfield but when I'm using the JComboBox the result won't display. How to use the StringTokenizer.nextElement() for JComboBox? Is is the same with TextField?
String sex=(String) stringTokenizer.nextElement();
I tried this code but still failed :(
You seem to have left out the relevant portions of your code, i.e. how you are handling setting/getting items in the JComboBox. Whether you read these values from a database, a file or have them hardcoded is irrelevant to the question.
Since you do ask whether it is the same as with a JTextField, I can at least answer this; it is not the same. The question indicates that you're quite new to Swing. You would probably benefit from working through a basic Swing tutorial, just to get a grip on how to work with these basic GUI elements. For JComboBox, check out Oracles own How to Use Combo Boxes.
Anyways, when working with JComboBox, you will need to first populate it with the values that users can choose from and set the currently selected value. Retrieving the currently selected value is just a simple method call.
Further, you have the possibility of making a combobox editable. This means that the user can edit the text in the combo box to something that was not pre-populated. By default, this option is turned off.
I'll provide some examples.
Initialize:
JComboBox sexComboBox = new JComboBox();
sexComboBox.addItem("Not selected");
sexComboBox.addItem("Male");
sexComboBox.addItem("Female");
sexComboBox.addItem("Do not want to disclose");
By default, the first item you added is selected. To select another one, you need to add one of the following lines:
sexComboBox.setSelectedIndex(1); // zero-based index, "Male" is selected item
sexComboBox.setSelectedItem("Female"); // sets the selected item to "Female"
To enable user to edit the contents to something that was not pre-defined, just add the line:
sexComboBox.setEditable(true);
To retrieve the currently selected value:
String selectedItem = (String) sexComboBox.getSelectedItem();

Best way to implement a selection box from a large number of entries

I have a large set of data from which the user has to select one. I'm thinking of a way to implement it (of course, in a GUI). I have a few ideas. But just thought of posting here as there may be better alternatives..
Say, user has to select a name from a large set of user base. If I simply put a text field for user to enter the name, then there can be issues like entering same name in different formats, misspelling etc...
I see two options here
Using a combo box
Using a list (Actually i'm thinking of something like a tool tip. As I cant show the whole list always due to space issues)
But combo box won't be much user friendly i guess. As the user will have to scroll around the whole list to select an entry. If the number of entries are too large, this will be
Which means, now I'm left only one option. A popping up list, which will change the content according the text user is entering in the text field. So he can type first few letters and the list will show all the entries starting from the entered text. Got my point, right?
Are there any other better to achieve this kind of need?
If I'm going to implement above, what will be the best way to follow. I'm thinking of extending the JTextField to add required functionality. Well, I'll put some method to set the popup list entries. And I'll add some actionListner to watch the text field, and control the popup list accordingly...
Autocomplete is what you are probably looking for. Google for "java swing jcombobox autocomplete" and limit results for the last couple of years to get relevant results. There will be a lot of examples and ideas on how to implement this with custom code.
I believe there is also some custom libraries like "swingx" that provide at least partial or full implementations to save time.
http://swingx.java.net/
They have released code as recently as the beginning of this years so it appears active and might have what you need.
You could take a look at SwingLab's autocomplete feature, it allows you to attach it to a JCombBox, JList or JTextComponent
use AutoComplete JComboBox/JTextField
based on Standard Java Classes
no issue with larger sets of data
no issue with Focus, BackSpace Key, Caret
for better performance to required sort the array before use
simple workaround for setStrict(true/false), restrict input to array

create link in table cell and open float popup by click from it

I have a CellTable and need a column with hyper links and onclick handlers inside cells.
1st question, what am doing wrong if I have:
Column<MyObject, Anchor> linkColumn = new Column<MyObject, Anchor>(
new AnchorCell()) {
#Override
public Anchor getValue(final obj) {
Anchor link = new Anchor("link");
link.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("clicked ");
}
});
return link;
}
};
cellTable.addColumn(linkColumn, "link column");
...
public class AnchorCell extends AbstractCell<Anchor> {
#Override
public void render(Context context, Anchor h, SafeHtmlBuilder sb) {
sb.append(SafeHtmlUtils.fromTrustedString(h.toString()));
}
}
-but clicking to link - happens nothing
and 2nd question: what's better way to open float (based on div or so, not separated browser window) pupup with text contents from that ClickHandler?
In a CellTable, you aren't adding the Anchor widget to the table. You're just adding some HTML. None of the widget's functions will work as they normally would, because the widget is not actually in the table.
You can override onBrowserEvent to get events like clicking on the cells. These events still happen because they are native to the browser and don't need the widget framework to propagate. I think this is the best way to achieve the effect you want.
I have a similar setup as you. A CellTable (now a DataGrid) with hyperlinks in it, but I want to popup an editor widget when the user clicks in the cell but not on the link-y bit. If he clicks on the link, I want the normal HTML behaviour.
Create your column using the ClickableTextCell class. What's stored in the cell? A string ID into my database of user records, which includes the name and email of the user. When I create the column, I override the render method so that the information is rendered as a email link:
Column<RowType, ColumnType> emailColumn = new Column<RowType, ColumnType>(new ClickableTextCell()){
#Override
public void render(Context context, T object, SafeHtmlBuilder sb) {
/* Code that pulls the value in this column at this row, uses
* it to look up the name and the email, then does sb.appendX
* to build up the "<a href='emaillink'>name</a>" SafeHtml
* construction.
*/
}
};
Actually, I have a subclass of Column, but you get the idea.
Voila, an active HTML link on your page, but a clickable text cell underneath. I found this a lot easier than dealing with browser events.
I use the same structure for many of my cells. ClickableTextCells underneath, and type-specific rendering code to present it to the user in the format expected. In particular, we have a dynamic picklist type of field -- that is, the picklist is not known until the click occurs. The standard selectionCell requires the list of picks to be established once at construction time, which is what got me to this solution. So instead of a standard SelectionCell dropdown, which wouldn't work anyway without some serious work**, I use this technique. When the ClickableTextCell fires, I have set the FieldUpdater to construct a popup with a DataGrid in it, this DataGrid listing the current set of legal values for this selection (as determined by the current state of the database). When the user makes his selection and hits the Save button, the popup closes, the middleware is called to update his choice, the updated row data is returned via that RPC call, the data returned being used to update the internal client-side database, which triggers an update of all the ListDataProviders driving the DataGrids, which automatically updates the main DataGrid (and any other DataGrid potentially visible on the screen).
Actually, my solution has extended the ClickableTextCell into a DoubleClickableTextCell so that you need to double-click to activate the editor. Not required, of course, but it allows for the user to idly click around the grid without popups exploding in front of him.
** Besides the dynamic aspect, this dynamic selections can be very long lists, so a dropdown is a poor choice. Better to present a DataGrid that the user can scroll through, search, filter, and so on.

Change color of JButton when selected, & Set mask on JFormattedTextField?

I'm writing my 1st Java program (in Netbeans) and I'm lost. I have 2 questions at the moment, if anyone is kind enough to help me.
Here's what the program is supposed to do:
take 1 of 4 "status" options, plus a 5 digit number (both of these items are entered by a user via a touch-screen monitor) and then email this info to someone with the subject line of: "Item #[5 digit number from JFormattedTextField] is currently [1 of 4 possible status options].
Email command would command after user clicks "enter" button, and then user clicks "OK" on a pop-up which asks user to confirm message about to be emailed. As far as my 3rd question, it's about the e-mailing part, and I figured that would be a another thread after I get this button & text field stuff ironed out.
Here's a picture of the touch screen UI I have so far:
(can't post images as a rookie, go to krisbunda.com/gui.png for this image)
Question #1:
the 4 status options (4 JButtons) are wrapped inside of a JPanel. I want the most recent button to have been pushed in the "statusPanel" JPanel to change the background to blue and the button text to white.
Can I put a mouselistener on the button's parent JPanel to listen for click events on the children (the 4 status JButtons), and then whichever button was last clicked, it will turn blue w/ white text? Please point me in the right direction.
Question #2:
I have a JFormattedTextField named "display" that shows the numbers as they're clicked, which are appended from a StringBuffer named "current". I want the text field to only accept a total of 5 numbers.
When I tried putting a mask of "#####" on the field, it would only chime a warning beep when I pushed the number pad's buttons. Currently I've chosen "Category: number" and "Format: custom" and then typed "#####" in the "Format:" field. This allows me to click number buttons and see their text displayed, but it doesn't stop me from typing more than 5 characters.
I'm doing this through the "Properties> FormatterFactory" dialog box. A screen shot is shown below:
(go to krisbunda.com/text-formatterFactory.png to view this image)
And here's the code I have so far:
(my post was too long with this code, so go to: krisbunda.com/java-sampleCode.txt to view)
Thanks in advance for any help!
Your code looks fine, and you already have fields set up to hold references to all your buttons, so now you just need to write the code inside the status setting buttons and then make them call a subroutine with the new status. This subroutine should then reset all the buttons to their default color and then set the special selected color on the button that corresponds to the new or existing status.
Edit: adding code here in response to your comment...
Firstly, never use == with Strings. You MUST use equals() otherwise when you get two Strings that are identical, but are different objects, they will not be the same and your comparisons will fail.
There are much better ways of coding this up, including using enums etc. but this should work for you:
// Reset all the buttons
outsideNotReadyButton.setBackground(...);
loadedButton.setBackground(...);
outsideReadyButton.setBackground(...);
shippedButton.setBackground(...);
// Now set the one of the button's colors conditionally
String status = ...
if(status.equals("SHIPPED")) {shippedButton.setBackground(Color.BLUE);}
else if(status.equals("LOADED")) {loadedButton.setBackground(Color.BLUE);}
// ...and so on
An ActionListener is the more common approach to buttons, as discussed in How to Use Buttons, etc. A FocusListener, also used in this example, is one way to change a button's appearance in the way you describe.
An sscce showing just your JFormattedTextField problem will be more helpful. Several such examples may be found in the article How to Use Formatted Text Fields.

Categories