Scrolling on VBox with lots of Textfields - mobile

I am having lots of Textfields in VBox in a Scrollpane. When scrolling and touching a textfields it just grabs the focus. So smooth scrolling is not possible. How can I get it nice scrolling without the unwanted focus on any textfield. Do I need to consume the events on the textfield while scrolling?

This is a possible solution for the case where you want to scroll over a long list of textfields, without letting them take the focus, until you stop scrolling at all, and clearly want to select one of the textfields.
It is based in a custom "press and hold" event, inspired by this question.
The idea is to bundle the TextField control in an HBox, and disable the access to the control using the mouse transparent property of the container.
Then, whenever you tap on the container, if you press long enough the container will give access to the control and the keyboard will show up. Otherwise, you will continue scrolling, but without showing the keyboard.
I'll use the KeyboardService referred in this question on iOS only.
public class BasicView extends View {
public BasicView(String name) {
super(name);
setTop(new Button("Button"));
VBox controls = new VBox(15.0);
controls.setAlignment(Pos.CENTER);
ScrollPane pane = new ScrollPane(controls);
controls.prefWidthProperty().bind(pane.widthProperty().subtract(20));
for (int i = 0; i < 100; i++) {
final Label label = new Label("TextField " + (i + 1));
final TextField textField1 = new TextField();
HBox.setHgrow(textField1, Priority.ALWAYS);
HBox box = new HBox(10, label, textField1);
box.setMouseTransparent(true);
box.setAlignment(Pos.CENTER_LEFT);
box.setPadding(new Insets(5));
controls.getChildren().add(box);
}
addPressAndHoldHandler(controls, Duration.millis(300), eStart -> {
for (Node box : controls.getChildren()) {
box.setMouseTransparent(true);
}
}, eEnd -> {
for (Node box : controls.getChildren()) {
if (box.localToScene(box.getBoundsInLocal()).contains(eEnd.getSceneX(), eEnd.getSceneY())) {
box.setMouseTransparent(false);
((HBox) box).getChildren().get(1).requestFocus();
break;
}
}
});
setCenter(pane);
// iOS only
Services.get(KeyboardService.class).ifPresent(keyboard -> {
keyboard.visibleHeightProperty().addListener((obs, ov, nv) -> {
if (nv.doubleValue() > 0) {
for (Node box : controls.getChildren()) {
Node n1 = ((HBox) box).getChildren().get(1);
if (n1.isFocused()) {
double h = getScene().getHeight() - n1.localToScene(n1.getBoundsInLocal()).getMaxY();
setTranslateY(-nv.doubleValue() + h);
break;
}
}
} else {
setTranslateY(0);
}
});
});
}
#Override
protected void updateAppBar(AppBar appBar) {
appBar.setNavIcon(MaterialDesignIcon.MENU.button(e -> System.out.println("Menu")));
appBar.setTitleText("Scrolling over TextFields");
}
private void addPressAndHoldHandler(Node node, Duration holdTime,
EventHandler<MouseEvent> handlerStart, EventHandler<MouseEvent> handlerEnd) {
class Wrapper<T> {
T content;
}
Wrapper<MouseEvent> eventWrapper = new Wrapper<>();
PauseTransition holdTimer = new PauseTransition(holdTime);
holdTimer.setOnFinished(event -> handlerEnd.handle(eventWrapper.content));
node.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
handlerStart.handle(event);
eventWrapper.content = event;
holdTimer.playFromStart();
});
node.addEventHandler(MouseEvent.MOUSE_RELEASED, event -> holdTimer.stop());
node.addEventHandler(MouseEvent.DRAG_DETECTED, event -> holdTimer.stop());
}
}
Note that I've added a button on top to get the focus on the first place when you show the view.
Whenever you click/tap on the controls VBox, it sets all the boxes mouse transparent: box.setMouseTransparent(true);, and start a PauseTransition.
If there is a mouse release or a mouse drag before 300 ms (this could be changed at your convenience), the transition will stop. Otherwise, after 300 ms, it will set the box to box.setMouseTransparent(false);, and set the focus on the TextField, and at that moment the keyboard will show up.

Here is a class which I use for the purpose you describe:
public class MouseClickedFilter{
private final Node observableNode;
private BooleanProperty scrolling = new ReadOnlyBooleanWrapper(false);
private EventHandler<? super MouseEvent> dragDetectedFilter = e -> scrolling.set(true);
private EventHandler<? super MouseEvent> mouseExitedHandler = e -> scrolling.set(false);
private EventHandler<? super MouseEvent> mouseClickedFilter = evt ->
{
if (scrolling.get()) {
evt.consume();
scrolling.set(false);
}
};
private boolean listenersEnabled;
public MouseClickedFilter(Node observableNode) {
this.observableNode = observableNode;
}
public void activate() {
if (!listenersEnabled) {
observableNode.addEventFilter(MouseEvent.DRAG_DETECTED, dragDetectedFilter);
observableNode.addEventHandler(MouseEvent.MOUSE_EXITED, mouseExitedHandler);
observableNode.addEventFilter(MouseEvent.MOUSE_CLICKED, mouseClickedFilter);
}
}
public void deactivate() {
if (listenersEnabled) {
observableNode.removeEventFilter(MouseEvent.DRAG_DETECTED, dragDetectedFilter);
observableNode.removeEventHandler(MouseEvent.MOUSE_EXITED, mouseExitedHandler);
observableNode.removeEventFilter(MouseEvent.MOUSE_CLICKED, mouseClickedFilter);
}
}
public final ReadOnlyBooleanProperty scrollingProperty() {
return scrolling;
}
public final boolean isScrolling() {
return scrolling.get();
}
}
ObservableNode is your ScrollPane containing the textFields

Related

Strange placement of multiple FloatingActionButton instances bound to the content pane

When binding mor than one FloatingActionButton instances to the content pane I notice a strange grouping effect.
Adding a the first at bottom left and the second at bottom right they are both grouped right.
Adding the first at bottom right and the second at bottom left they are grouped left in creation order.
Is this behaviour to be expected and why then or is it a bug?
Here's the code:
public class FormMultipleFloatingButtons extends Form {
public FormMultipleFloatingButtons() {
this(true);
}
public FormMultipleFloatingButtons(boolean aLeftBeforeRight) {
setTitle("Button Placement");
setScrollable(false);
Container contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
contentPane.setScrollableY(true);
Style style = contentPane.getAllStyles();
style.setMarginUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
style.setMargin(5, 5, 5, 5);
style.setBorder(Border.createDashedBorder(1));
TextArea textArea = new TextArea(
"The placement of FloatingActionButtons when adding more than one of those.\n\n"
+ "Tap the right toolbar button to recreate the form with swapped creation order "
+ "of the two FloatingActionButton instances.");
textArea.setEditable(false);
contentPane.add(textArea);
Runnable runnableLeft = () -> {
FloatingActionButton floatingActionButton = FloatingActionButton.createFAB(
FontImage2.MATERIAL_CALL_RECEIVED);
floatingActionButton.bindFabToContainer(contentPane, Component.LEFT, Component.BOTTOM);
};
Runnable runnableRight = () -> {
FloatingActionButton floatingActionButton = FloatingActionButton.createFAB(
FontImage2.MATERIAL_SUBDIRECTORY_ARROW_RIGHT);
floatingActionButton.bindFabToContainer(contentPane, Component.RIGHT, Component.BOTTOM);
};
if (aLeftBeforeRight) {
runnableLeft.run();
runnableRight.run();
} else {
runnableRight.run();
runnableLeft.run();
}
getToolbar().addCommandToRightBar(new Command(
"",
FontImage.createMaterial(FontImage.MATERIAL_SWAP_HORIZ, style)) {
#Override
public void actionPerformed(ActionEvent evt) {
FormMultipleFloatingButtons formMultipleFloatingButtons = new FormMultipleFloatingButtons(!aLeftBeforeRight);
formMultipleFloatingButtons.show();
}
});
}
}
The content pane only supports one FloatingActionButton. Since adding a fab to the content pane places it in the layered pane and that is an exclusive position adding two fabs cause a collision.
This isn't something we designed for as the UX of FAB is pretty clear that there should be just one and if more functionality is needed you can add it below.
If you still want to do this you can use a Container within the content pane and bind to that.
To have a "next" and "previous" FloatingActionButton to scroll through my tabs, I did the following:
private FloatingActionButton fabRight = FloatingActionButton.createFAB(FontImage.MATERIAL_KEYBOARD_ARROW_RIGHT);
private FloatingActionButton fabLeft = FloatingActionButton.createFAB(FontImage.MATERIAL_KEYBOARD_ARROW_LEFT);
tabs.addSelectionListener((i1, i2) -> {
fabRight.setVisible(i2 != tabs.getTabCount() - 1);
fabLeft.setVisible(i2 != 0);
});
fabRight.addActionListener(e -> {
int index = tabs.getSelectedIndex() + 1;
tabs.setSelectedIndex(index);
fabRight.setVisible(index != tabs.getTabCount() - 1);
});
fabLeft.addActionListener( e -> {
int index = tabs.getSelectedIndex() -1;
tabs.setSelectedIndex(index);
fabLeft.setVisible(index != 0);
});
Container cntRight = fabRight.bindFabToContainer(tabs,Component.RIGHT, Component.BOTTOM);
Container cntLeft = fabLeft.bindFabToContainer(cntRight,Component.LEFT, Component.BOTTOM);
BorderLayout bl = new BorderLayout();
bl.setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER);
setLayout(bl);
add(BorderLayout.CENTER, cntLeft);
add(BorderLayout.SOUTH, cntButtons);

Codename One Back Command on left and Menu on Right

i am trying to make an app in Codename one where i want to create a handburger menu on the right side at the top of the screen and a back button on the left side, but cannot get it to work I know it can be done where you have a handburger menu on the left side and a button on the right side. I made a picture of how I want it to look like. The back button is added in paint and not through the code.
Picture of app example
below is the code that I have used to get the menu on the right side.
public class MainForm {
public static Form mainForm;
Command cmd_back, cmd_AboutTheApp;
private enum SideMenuMode {
SIDE, RIGHT_SIDE {
public String getCommandHint() {
return SideMenuBar.COMMAND_PLACEMENT_VALUE_RIGHT;
}
};
public String getCommandHint() {
return null;
}
public void updateCommand(Command c) {
String h = getCommandHint();
if(h == null) {
return;
}
c.putClientProperty(SideMenuBar.COMMAND_PLACEMENT_KEY, h);
}
};
SideMenuMode mode = SideMenuMode.RIGHT_SIDE;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
UIManager.getInstance().setThemeProps(theme.getTheme theme.getThemeResourceNames()[0]));
UIManager.getInstance().getLookAndFeel().setMenuBarClass(SideMenuBar.class);
Display.getInstance().setCommandBehavior(Display.COMMAND_BEHAVIOR_SIDE_NAVIGATION);
}
public void start() {
if(mainForm != null){
mainForm.show();
return;
}
mainForm = new Form();
mainForm.setTitleComponent(title);
mainForm.setLayout(new BorderLayout());
addCommands(mainForm);
}
private void addCommands(Form f){
cmd_Back = new Command("Back");
final Button btn_Back = new Button("Back");
cmd_Back.putClientProperty("TitleCommand", btn_Back);
btn_BackButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do some thing
}
});
cmd_AboutTheApp = new Command("About the app");
final Button btn_AboutTheApp = new Button("About the app");
cmd_AboutTheApp.putClientProperty("SideComponent", btn_AboutTheApp);
btn_AboutTheApp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do some thing
}
});
mode.updateCommand(cmd_Back);
f.addCommand(cmd_Back);
mode.updateCommand(cmd_AboutTheApp);
f.addCommand(cmd_AboutTheApp);
}
}
if I move the back button so that it is added after AboutTheApp button then the back button is displayed on the right side of the screen but also to the right of the menu, which is also on the right side. I've tried a lot of different ways but none seems to be working
We supported a right side menu bar in the SideMenuBar but not in the Toolbar API. We support placing components/commands in the left/right side of the title area in the Toolbar API but not in the SideMenuBar.
I guess the solution is to add support for the right menu bar into the Toolbar API but I'm not sure what the complexities are for such a change.
I suggest filing an RFE in the issue tracker asking for this but it probably won't be soon as we are closing the features for 3.3 right now.
I have an app that does this. Search Google Play (or App Store) for "Torquepower Diesel Cummins Engine" app.
in the theme Constants I set my own rightSideMenuImage and rightSideMenuPressImage, but the default hamburger menu may be OK for you.
On the beforeXXXX of each form I do something like this:
super.beforePartNumberForm(f);
Toolbar tb = createToolbar(f);
createBackCommand(f, tb);
addHelpX(tb);
addViewCartX(tb);
addCallTorquepowerX(tb);
addReverseSwipe(f);
create the toolbar
Toolbar createToolbar(Form f) {
Toolbar tb = new Toolbar();
f.setToolBar(tb);
Label l = new Label();
l.setIcon(res.getImage("tpd_logoZZ.png"));
tb.setTitleComponent(l);
return tb;
}
create the back button
void createBackCommand(Form f, Toolbar tb) {
Command c = new Command("") {
#Override
public void actionPerformed(ActionEvent evt) {
back();
}
};
c.setIcon(res.getImage("black_left_arrow-512.png"));
c.setPressedIcon(res.getImage("grey_left_arrow-512.png"));
// MUST set this before adding to toolbar, else get null pointer
f.setBackCommand(c);
tb.addCommandToLeftBar(c);
}
add whatever commands are needed to the sidemenu
void addHelpX(Toolbar tb) {
Command c = new Command("Help") {
#Override
public void actionPerformed(ActionEvent evt) {
showForm("HelpForm", null);
}
};
c.putClientProperty(SideMenuBar.COMMAND_PLACEMENT_KEY, SideMenuBar.COMMAND_PLACEMENT_VALUE_RIGHT);
c.putClientProperty("SideComponent", new SideMenuItem(fetchResourceFile(), c.toString(), "very_basic_about.png"));
c.putClientProperty("Actionable", Boolean.TRUE);
tb.addCommandToSideMenu(c);
}
I use my own SideMenuItem which is:
public class SideMenuItem extends Button {
SideMenuItem() {
this("");
}
SideMenuItem(String s) {
super(s);
setUIID("SideMenuItem");
int h = Display.getInstance().convertToPixels(8, false);
setPreferredH(h);
}
SideMenuItem(Resources res, String s, String icon) {
super();
setIcon(res.getImage(icon));
setText(s);
setUIID("SideMenuItem");
int h = Display.getInstance().convertToPixels(8, false);
setPreferredH(h);
}
}

JavaFX 8: ComboBox button cell update behavior

I have a combo box which contains items of type Dog. If all items are replaced with new ones (via setAll on the ObservableList model) , the item renderer can cope with this update, while the button cell renderer cannot:
Here's a minimal example to reproduce the problem (full source incl. imports on GitHub):
public class ComboBoxRefresh extends Application {
private static final class Dog {
private final String name;
public Dog(String name) {
this.name = name;
}
}
private static final class DogListCell extends ListCell<Dog> {
#Override
public void updateItem(Dog item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText("");
} else {
setText(item.name);
}
}
}
private static List<Dog> createThreeDogs() {
return range(0, 3).mapToObj(i -> new Dog("Buddy " + i)).collect(toList());
}
#Override
public void start(Stage stage) throws Exception {
ObservableList<Dog> items = observableArrayList(createThreeDogs());
ComboBox<Dog> comboBox = new ComboBox<>(items);
comboBox.setPrefWidth(400);
comboBox.setCellFactory(listView -> new DogListCell());
comboBox.setButtonCell(new DogListCell());
Button button = new Button("Refresh");
button.setOnAction(event -> {
List<Dog> newItems = createThreeDogs();
items.setAll(newItems);
});
VBox box = new VBox(10, comboBox, button);
box.setPadding(new Insets(10));
Scene scene = new Scene(box);
stage.setScene(scene);
stage.show();
}
}
If I add an equals implementation to the Dog class, everything works, but this is not an option in my real application.
Are there any work-arounds to enforce a proper refresh of the button cell?
It seems to be a bug. Workaround could be
button.setOnAction( event -> {
List<Dog> newItems = createThreeDogs();
items.clear();
items.addAll(newItems);
} );

How to avoid closing popup menu on mouse clicking in javafx combobox?

I have combobox with custom ListCell:
private class SeverityCell extends ListCell<CustomItem> {
private final CustomBox custombox;
{
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
custombox = new CustomBox();
}
#Override
protected void updateItem(CustomItem item, boolean empty) {
super.updateItem(item, empty);
if (null != item) {
//...
}
setGraphic(custombox);
}
}
and
combobox.setCellFactory(new Callback<ListView<CustomItem>, ListCell<CustomItem>>() {
#Override public ListCell<CustomItem> call(ListView<CustomItem> p) {
return new SeverityCell();
}
});
When I click on mu custom component popup closes, but I want to avoid it. Which method/event I need to override?
ComboBox internally utilizes ListView for rendering its items. Also its skin class is ComboBoxListViewSkin. In a source code of this class there is boolean flag to control popup hiding behavior:
// Added to allow subclasses to prevent the popup from hiding when the
// ListView is clicked on (e.g when the list cells have checkboxes).
protected boolean isHideOnClickEnabled() {
return true;
}
which is used on listview:
_listView.addEventFilter(MouseEvent.MOUSE_RELEASED, t -> {
// RT-18672: Without checking if the user is clicking in the
// scrollbar area of the ListView, the comboBox will hide. Therefore,
// we add the check below to prevent this from happening.
EventTarget target = t.getTarget();
if (target instanceof Parent) {
List<String> s = ((Parent) target).getStyleClass();
if (s.contains("thumb")
|| s.contains("track")
|| s.contains("decrement-arrow")
|| s.contains("increment-arrow")) {
return;
}
}
if (isHideOnClickEnabled()) {
comboBox.hide();
}
});
So the behavior you want can be (and probably should be) implemented with custom skin. However, the workaround can be
combobox.setSkin( new ComboBoxListViewSkin<CustomItem>( combobox )
{
#Override
protected boolean isHideOnClickEnabled()
{
return false;
}
} );
and manually hide the popup, when the value is changed for instance:
combobox.valueProperty().addListener( new ChangeListener()
{
#Override
public void changed( ObservableValue observable, Object oldValue, Object newValue )
{
combobox.hide();
}
});
Note please, I didn't fully test this anonymous inner skin approach.

Button Click Event Getting Lost

I have a Menu and Submenu structure in Silverlight, and I want the submenu to disappear when the parent menu item loses focus - standard Menu behavior. I've noticed that the submenu's click events are lost when a submenu item is clicked, because the parent menu item loses focus and the submenu disappears.
It's easier to explain with code:
ParentMenuBtn.Click += delegate
{
SubMenu.Visibility = (SubMenu.Visibility == Visibility.Visible) ? SubMenu.Collapsed : SubMenu.Visible;
};
ParentMenuBtn.LostFocus += delegate
{
SubMenu.Visibility = Visibility.Collapsed;
};
SubMenuBtn.Click += delegate
{
throw new Exception("This will never be thrown.");
};
In my example, when SubMenuBtn is clicked, the first event that triggers is ParentMenuBtn.LostFocus(), which hides the container of SubMenuBtn. Once the container's visibility collapses, the Click event is never triggered.
I'd rather avoid having to hide the sub-menu each time, but I'm a little surprised that the Click event is never triggered as a result...
I can't put any checks inside the LostFocus() event to see if my SubMenuBtn has focus, because it does not gain focus until after the LostFocus() event is called. In other words, SubMenuBtn.IsFocused = false when LostFocus() is triggered.
Anyone have any thoughts about this?
I've found out the solution - albeit, it's not as simple, or elegant as I would have liked. The solution is to use a secondary thread that pauses only for a moment before executing.
ie.
public partial class Navigation : UserControl
{
public Navigation()
{
ParentMenuBtn.Click += delegate
{
SubMenu.Visibility = (SubMenu.Visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;
};
ParentMenuBtn.LostFocus += delegate(object sender, RoutedEventArgs e)
{
HideSubMenu(SubMenu);
};
SubMenuBtn.Click += delegate
{
//Sub Menu Button actions...
};
private void HideSubMenu(UIElement subMenu)
{
//Get the Main Page
App app = (App)Application.Current;
MainPage mainPage = (MainPage)app.RootVisual;
Thread thread = new Thread(Navigation.HideSubMenu);
thread.Start(new ThreadState(mainPage, subMenu));
}
private static void HideSubMenu(object threadStateObj)
{
ThreadState threadState = (ThreadState)threadStateObj;
//Execute after 5 milliseconds...
System.Threading.Thread.Sleep(5);
threadState.MainPage.Dispatcher.BeginInvoke(delegate() {
threadState.TargetElement.Visibility = Visibility.Collapsed;
});
}
I just use a simple object called ThreadState to handle all the state objects I want to preserve:
public class ThreadState
{
public MainPage MainPage = null;
public UIElement TargetElement = null;
public ThreadState(MainPage mainPage, UIElement targetElement)
{
this.MainPage = mainPage;
this.TargetElement = targetElement;
}
}

Resources