I want to use a JavaFX TextArea as though it were exactly like a multi-line TextField. In other words, when I press [Tab] I want to cycle to the next control on the form and when I press [Enter] I want the Key.Event to go to the defaultButton control (rather than be consumed by the TextArea).
The default behavior for TextArea is that [Tab] gets inserted into the TextArea and [Enter] inserts a new-line character.
I know that I need to use EventFilters to get the behavior that I want, but I'm getting it all wrong. I don't want the TextArea to consume these events ... I just want it to let them "go right on by".
The solution here displays two text areas and a default button.
When the user presses the tab key, the focus moves to the next control down.
When the user presses the enter key, the default button is fired.
To achieve this behavior:
The enter key press for each text area is caught in an event filter, copied and targeted to the text area's parent node (which contains the default OK button). This causes the default OK button to be fired when enter is pressed anywhere on the form. The original enter key press is consumed so that it does not cause a new line to be added to the text area's text.
The tab key press for each text area is caught in a filter and the parent's focus traversable list is processed to find the next focusable control and focus is requested for that control. The original tab key press is consumed so that it does not cause new tab spacing to be added to the text area's text.
The code makes use of features implemented in Java 8, so Java 8 is required to execute it.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.value.*;
import javafx.collections.ObservableList;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import static javafx.scene.input.KeyCode.ENTER;
import static javafx.scene.input.KeyCode.TAB;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.*;
public class TextAreaTabAndEnterHandler extends Application {
final Label status = new Label();
public static void main(String[] args) { launch(args); }
#Override public void start(final Stage stage) {
final TextArea textArea1 = new TabAndEnterIgnoringTextArea();
final TextArea textArea2 = new TabAndEnterIgnoringTextArea();
final Button defaultButton = new Button("OK");
defaultButton.setDefaultButton(true);
defaultButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
status.setText("Default Button Pressed");
}
});
textArea1.textProperty().addListener(new ClearStatusListener());
textArea2.textProperty().addListener(new ClearStatusListener());
VBox layout = new VBox(10);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10px;");
layout.getChildren().setAll(
textArea1,
textArea2,
defaultButton,
status
);
stage.setScene(
new Scene(layout)
);
stage.show();
}
class ClearStatusListener implements ChangeListener<String> {
#Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
status.setText("");
}
}
class TabAndEnterIgnoringTextArea extends TextArea {
final TextArea myTextArea = this;
TabAndEnterIgnoringTextArea() {
addEventFilter(KeyEvent.KEY_PRESSED, new TabAndEnterHandler());
}
class TabAndEnterHandler implements EventHandler<KeyEvent> {
private KeyEvent recodedEvent;
#Override public void handle(KeyEvent event) {
if (recodedEvent != null) {
recodedEvent = null;
return;
}
Parent parent = myTextArea.getParent();
if (parent != null) {
switch (event.getCode()) {
case ENTER:
if (event.isControlDown()) {
recodedEvent = recodeWithoutControlDown(event);
myTextArea.fireEvent(recodedEvent);
} else {
Event parentEvent = event.copyFor(parent, parent);
myTextArea.getParent().fireEvent(parentEvent);
}
event.consume();
break;
case TAB:
if (event.isControlDown()) {
recodedEvent = recodeWithoutControlDown(event);
myTextArea.fireEvent(recodedEvent);
} else {
ObservableList<Node> children = parent.getChildrenUnmodifiable();
int idx = children.indexOf(myTextArea);
if (idx >= 0) {
for (int i = idx + 1; i < children.size(); i++) {
if (children.get(i).isFocusTraversable()) {
children.get(i).requestFocus();
break;
}
}
for (int i = 0; i < idx; i++) {
if (children.get(i).isFocusTraversable()) {
children.get(i).requestFocus();
break;
}
}
}
}
event.consume();
break;
}
}
}
private KeyEvent recodeWithoutControlDown(KeyEvent event) {
return new KeyEvent(
event.getEventType(),
event.getCharacter(),
event.getText(),
event.getCode(),
event.isShiftDown(),
false,
event.isAltDown(),
event.isMetaDown()
);
}
}
}
}
An alternate solution would be to implement your own customized skin for TextArea which includes new key handling behavior. I believe that such a process would be more complicated than the solution presented here.
Update
One thing I didn't really like about my original solution to this problem was that once the Tab or Enter key was consumed, there was no way to trigger their default processing. So I updated the solution such that if the user holds the control key down when pressing Tab or Enter, the default Tab or Enter operation will be performed. This updated logic allows the user to insert a new line or tab space into the text area by pressing CTRL+Enter or CTRL+Tab.
Related
I'm at complete loss how to proceed further:
I have panel with a DropDownChoice and a submit button next to it. Depending on the selected value of the DropDownChoice (Obtained upon the firing of a OnChangeAjaxBehavior attached to it, the submit button needs to either replace the whole panel with a different one, OR become an ExternalLink.
Currently, the code looks like that:
public class ReportSelectionPanel extends Panel {
protected OptionItem selectedOption ;
public ReportSelectionPanel(String id) {
super(id);
IModel<List<OptionItem>> choices = new AbstractReadOnlyModel() {
// Create a list of options to be displayed in the DropDownChoice
} ;
final IModel<OptionItem> optionModel =
new PropertyModel<OptionItem>(this,"selectedOption") ;
final DropDownChoice<OptionItem> options =
new DropDownChoice("selectChoice",optionModel,choices) ;
// I don't know what the button should be... Plain Button? A Link?
final Component button = ???
options.add( new OnChangeAjaxBehavior() {
protected void onUpdate(AjaxRequestTarget target) {
if ( selectedOption.getChild() == null ) {
// button becomes an ExternalLink.
// A new window will popup once button is clicked
} else {
// button becomes a Something, and upon clicking,
// this ReportSelectionPanel instance gets replaced by
// an new Panel instance, the type of which is
// selectedOption.getChild()
}
} ) ;
I'm really not quite sure what the commented lines should become to achieve the result. Any suggestions?
Thanks!
Eric
IMHO it's nicer to keep just one button and just react differently depending on the selected option:
final Component button = new AjaxButton("button") {
public void onClick(AjaxRequestTarget target) {
if (selectedOption.getChild() == null) {
PopupSettings popup = new PopupSettings();
popup.setTarget("'" + externalUrl + "'");
target.appendJavascript(popup.getPopupJavaScript());
} else {
ReportSelectionPanel.this.replaceWith(new ReportResultPanel("..."));
}
}
};
// not needed if options and button are inside a form
// options.add( new OnChangeAjaxBehavior() { } ) ;
we would like to link from a CellTable to a property editor page. We use the SingleSelectionModel to get notified, when a user clicks on an item.
It is initialized like this:
private final SingleSelectionModel<Device> selectionModel = new SingleSelectionModel<Device>();
We then assign the selection change handler:
selectionModel.addSelectionChangeHandler(this);
Our selection change handler looks like this:
#Override
public void onSelectionChange(SelectionChangeEvent event) {
Log.debug("DevicesPresenter: SelectionChangeEvent caught.");
Device selectedDevice = selectionModel.getSelectedObject();
if (selectedDevice != null) {
selectionModel.clear();
if (selectionModel.getSelectedObject() != null){
Log.debug("DevicesPresenter: selected item is " + selectionModel.getSelectedObject());
}
else{
Log.debug("DevicesPresenter: selected item is null");
}
deviceEditorDialog.setCurrentDevice(selectedDevice.getUuid());
// get the container data for this device
clientModelProvider.fetchContainersForDevice(selectedDevice.getUuid());
PlaceRequest request = new PlaceRequest.Builder()
.nameToken(NameTokens.deviceInfo)
.with("uuid", selectedDevice.getUuid())
.build();
Log.debug("Navigating to " + request.toString());
placeManager.revealPlace(request);
}
}
Now there are two issues: There always seem to be two SelectionChangeEvents at once and i really cannot see why. The other thing is: How is the right way do handle selection of items and the related clearing of the selection model? Do we do that the right way?
Thanks!
If you only want to get notified of "clicks" without keeping the "clicked" item selected, use a NoSelectionModel instead; no need to clear the selection model as soon as something is selected.
As for your other issue with being called twice, double-check that you haven't added your selection handler twice (if you can unit-test your DevicesPresenter, introspect the handlers inside the selection model for example)
In your line selectionModel.addSelectionChangeHandler(this); what does this refer?
Here my code how I use SingleSelectionModel
public class MyClass{
private final SingleSelectionModel<CountryDto> selectionModel = new SingleSelectionModel<CountryDto>();
...
public MyClass(){
cellTable.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
#Override
public void onSelectionChange(SelectionChangeEvent event) {
CountryDto selected = selectionModel
.getSelectedObject();
if (selected != null) {
Window.alert("Selected country "+selected.getTitle());
}
}
});
}
}
Is there an easy way of preventing an accordion in JavaFX 2.1 from fully collapsing? I have an accordion with a few entries but if the user clicks the active accordion entry it collapses the accordion.
I could probably use a mouse click listener to check do the check and act accordingly but this feels like it should be even simpler than that to accomplish.
Add a listener to the currently expanded accordion pane and prevent it from being collapsed by the user by modifying it's collapsible property.
Here is a sample app:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class AccordionSample extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage primaryStage) {
// create some titled panes to go in an accordion.
TitledPane adminPane = new TitledPane("Animals",
VBoxBuilder.create().style("-fx-padding: 10").spacing(10).children(
ButtonBuilder.create().text("Zebra").maxWidth(Double.MAX_VALUE).build(),
ButtonBuilder.create().text("Shrew").maxWidth(Double.MAX_VALUE).build()
).build()
);
TitledPane viewPane = new TitledPane("Vegetables",
VBoxBuilder.create().style("-fx-padding: 10").spacing(10).children(
ButtonBuilder.create().text("Eggplant").maxWidth(Double.MAX_VALUE).build(),
ButtonBuilder.create().text("Carrot").maxWidth(Double.MAX_VALUE).build()
).build()
);
// create an accordion, ensuring the currently expanded pane can not be clicked on to collapse.
Accordion accordion = new Accordion();
accordion.getPanes().addAll(adminPane, viewPane);
accordion.expandedPaneProperty().addListener(new ChangeListener<TitledPane>() {
#Override public void changed(ObservableValue<? extends TitledPane> property, final TitledPane oldPane, final TitledPane newPane) {
if (oldPane != null) oldPane.setCollapsible(true);
if (newPane != null) Platform.runLater(new Runnable() { #Override public void run() {
newPane.setCollapsible(false);
}});
}
});
for (TitledPane pane: accordion.getPanes()) pane.setAnimated(false);
accordion.setExpandedPane(accordion.getPanes().get(0));
// layout the scene.
StackPane layout = new StackPane();
layout.setStyle("-fx-padding: 10; -fx-background-color: cornsilk;");
layout.getChildren().add(accordion);
primaryStage.setScene(new Scene(layout));
primaryStage.show();
}
}
Here is another solution for making sure the accordion will never completely collapse. The difference from the great original answer by #jewelsea is little - I didn't like the fact that the default down facing arrow was disappearing from the open accordion TitledPane face, because its "collapsible" property is being set to false. I played with it a bit more to achieve a more "natural" feel for my interface.
/* Make sure the accordion can never be completely collapsed */
accordeon.expandedPaneProperty().addListener((ObservableValue<? extends TitledPane> observable, TitledPane oldPane, TitledPane newPane) -> {
Boolean expand = true; // This value will change to false if there's (at least) one pane that is in "expanded" state, so we don't have to expand anything manually
for(TitledPane pane: accordeon.getPanes()) {
if(pane.isExpanded()) {
expand = false;
}
}
/* Here we already know whether we need to expand the old pane again */
if((expand == true) && (oldPane != null)) {
Platform.runLater(() -> {
accordeon.setExpandedPane(oldPane);
});
}
});
I have a user form with a lot of gwt listbox. The form is like an excel form with named list.
It's ugly and the arrows take place.
I would like the cells were like in excel. The arrow appears only when you click in the cell.
I start to program my own widget with a textbox and a listbox embedded into a DeckPanel, switching when you click on the textbox or when the value change. But with this solution, it is necessary to click again to open the listbox.
Now, it will be great, if when you click on the textbox, the listbox will be displayed already open.
In the code below, I try to do this into the method onClick wih this line:
DomEvent.fireNativeEvent(event.getNativeEvent(), listBox);
But it has no effects.
public class CustomListBox extends Composite implements ClickHandler,
ChangeHandler, HasChangeHandlers {
private final StringListBox listBox;
private final TextBox textBox;
private final DeckPanel panel;
public CustomListBox() {
textBox = new TextBox();
textBox.addClickHandler(this);
textBox.setReadOnly(true);
listBox = new StringListBox();
listBox.addChangeHandler(this);
panel = new DeckPanel();
panel.add(textBox);
panel.add(listBox);
panel.showWidget(0);
// All composites must call initWidget() in their constructors.
initWidget(panel);
}
#Override
public void onClick(ClickEvent event) {
Object sender = event.getSource();
if (sender == textBox) {
panel.showWidget(1);
DomEvent.fireNativeEvent(event.getNativeEvent(), listBox);
}
}
public void addItem(String item) {
listBox.addItem(item);
}
public int getSelectedIndex() {
return listBox.getSelectedIndex();
}
public String getItemText(int selectedIndex) {
return listBox.getItemText(selectedIndex);
}
#Override
public HandlerRegistration addChangeHandler(ChangeHandler handler) {
return listBox.addChangeHandler(handler);
}
#Override
public void onChange(ChangeEvent event) {
Object sender = event.getSource();
if (sender == listBox) {
textBox.setText(getItemText(getSelectedIndex()));
panel.showWidget(0);
}
}
}
Since you are already programming your own widget, why don't you go all the way. Don't swap out the text box for a list box widget. Instead of a textbox use a label. Add an arrow to your label background when you mouse over, then use a popupPanel for the list itself. In the popupPanel you can make the list items whatever you like, just make sure when you click on it, it sets the text in your original label.
I'm pretty new to GWT, but I've been making pretty fast progress until now.
I have a cell table, most of which is read only data returned from an RPC.
I have two columns in the cell table that the user can interact with. One is a TextInputCell, one is a ButtonCell.
When the user clicks the ButtonCell, i want to send the value in the TextInputCell for that row to an RPC.
I have all this working.
The part I cannot get to work is that when the button (ButtonCell) is clicked, I want to disable the button in that row until the RPC returns, and then re-enable it. I also want to clear the text in the input cell for that row when the RPC returns.
I cannot figure out how to get handles to the actual ButtonCell object that was clicked or the TextInputCell to monkey with them.
Any help appreciated.
bq
The problem is that there's no object for the button that was clicked. Your ButtonCell creates HTML that renders buttons - every button in the whole column was written by the same button cell, but there's no java object associated with them.
To disable the button directly, you'll have to first create a handle to it. You could do this by rendering an id in the html your ButtonCell creates, and then getting the element by id from the DOM.
What I do in a similar case is just re-render the entire table when there's a state change. It doesn't take that long, and you don't need to store any references (the whole reason you're using CellTable instead of Grid anyway). When you know your button should be disabled, you just render it disabled.
Both of these suggestions would require you to subclass your Cell objects so that you can do some custom rendering. It's not very difficult, but wrapping your head around the order of operations can be confusing. Good luck!
PS: If you just want to disable the button (and not empty the text field), I think onBrowserEvent gives you a handle to the Element that was clicked - you might be able to use that to disable it.
I have gone through this problem, but eventually I solved it.
check this code
package com.ex7.client;
import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
public class CWButton extends ButtonCell {
private int row = -1;
private String alternativevalue;
private String exTitle = "";
private String value;
private String title = "";
public CWButton( ) {
super();
}
#Override
public void render(com.google.gwt.cell.client.Cell.Context context,
String src, SafeHtmlBuilder sb) {
if (row == -1) {
sb.appendHtmlConstant("<button title='" + title + "' >" +value+"</button>");
return;
}
if (row != context.getIndex()) {
sb.appendHtmlConstant("<Button disabled='disabled' title='" + title + "' >"+ value+"</button>");
} else {
sb.appendHtmlConstant("<button title='" + exTitle + "' >"+ alternativevalue+"</button>");
}
}
#Override
public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context,
Element parent, String value, NativeEvent event,
ValueUpdater<String> valueUpdater) {
if (row == -1 || row == context.getIndex()) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
return;
}
}
public void setTitle(String title) {
this.title = title;
}
public int getRow() {
return row;
}
public String getExTitle() {
return exTitle;
}
public void setExTitle(String exTitle) {
this.exTitle = exTitle;
}
public void setRow(int row) {
this.row = row;
}
public String getAlternativeValue() {
return alternativevalue;
}
public void setAlternativeValue(String alternativeValue) {
this.alternativevalue = alternativeValue;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}