Grid's removeAllItems not working properly

I am not sure if I did something recently or what happened, but I could have sworn that this was working fine before. When I try calling the following function to remove all items, it doesn’t work properly:

myGrid.getContainerDataSource().removeAllItems();

It removes the items from the Grid, but when I then try to set the datasource, I see all my old items as well as the new. Here’s how I do that:

myGrid.setContainerDataSource(container);

Am I missing something? Did I screw something up elsewhere? Any thoughts would be most appreciated.

Just in case, the container above is a BeanItemContainer, and I am using the current Alpha2 release (still waiting for that Alpha4 to hit Maven, by the way).

Hi Dan,

First of all, the maven repository for the Vaadin Prereleases has changed. Check out instructions on how to get those at
https://vaadin.com/releases
.

For the remove all items issue, the issue should not be related to Grid, as there already is monitoring for all kind of changes in the container. Is the old data somehow existing in the new container you are setting? A simple example UI with this issue happening would speed up the debugging progress if you can provide one.

//Teemu

Hi Teemu. Thanks for the response. Regarding the prereleases, I am now using alpha4, so its all good.

More importantly, the remove items. I have tried various ways of removing the items … calling removeAllItems(), iterating through them individually and removing, resetting the grid to “new Grid()”, and even some other tricks mentioned online, but none of them worked. It seems this problem is relatively common, with various posts about this online. Maybe I am just doing something wrong somewhere else? I will copy my class in its entirety below, but its pretty big with lots of class dependencies, so …

Again, I would like to point out that calling the function does remove items from the grid. The problem is that when you try to add new items to the grid, the old items re-appear. After removing the items, we do some processing to generate a new list, then execute the following code to repopulate the grid:

        container = new BeanItemContainer<>(ComplexModuleData.class, complexes);
        complexGrid.setContainerDataSource(container);

Well, maybe I am doing something wrong? I have copied all my code below, but it is quite long so be warned. If you have any thoughts on a different approach, please let me know.

package org.ici.weekly.ui.weekly;

import com.google.common.collect.Maps;
import com.google.gwt.thirdparty.guava.common.base.Predicate;
import com.google.gwt.thirdparty.guava.common.collect.Iterables;
import com.google.gwt.thirdparty.guava.common.eventbus.Subscribe;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.event.*;
import com.vaadin.external.org.slf4j.Logger;
import com.vaadin.external.org.slf4j.LoggerFactory;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.*;
import com.vaadin.ui.renderers.ButtonRenderer;
import com.vaadin.ui.renderers.NumberRenderer;
import org.ici.weekly.App;
import org.ici.weekly.Util;
import org.ici.weekly.WeeklySecurityUtils;
import org.ici.weekly.db.WeeklyDAO;
import org.ici.weekly.db.domain.ComplexFund;
import org.ici.weekly.db.domain.ComplexLookup;
import org.ici.weekly.events.*;
import org.ici.weekly.ui.listeners.*;
import org.ici.weekly.ui.windows.ConfirmationWindow;
import org.joda.time.DateTime;

import javax.inject.Inject;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

public class ComplexGridModule extends Panel implements View {

    private static final Logger logger = LoggerFactory.getLogger(ComplexGridModule.class);

    private static WeeklyDAO dao = null;

    private static final String VIEW_ONLY = "View Only";
    private static final String UPDATEABLE = "Updateable";
    private static final String ETF = "ETF";
    private static final String MUTUAL = "Mutual";
    private static final String BOTH = "Both";
    private static final String MMKT = "MMKT";
    private static final String CONVENT = "Convent";
    private static final String FILTERED = "Filtered";
    private static final String ALL_DATA = "All Data";

    private List<String> updateList = Arrays.asList(VIEW_ONLY, UPDATEABLE);
    private List<String> fundList = Arrays.asList(ETF, MUTUAL, BOTH);
    private List<String> mutualFundList = Arrays.asList(MMKT, CONVENT, BOTH);
    private List<String> filterList = Arrays.asList(FILTERED, ALL_DATA);

    private Label complexNameLabel = new Label("Complex Name: ");
    private TextField complexNameText = new TextField();
    private Label flowParticipantLabel = new Label("Flow Participant: ");
    private TextField flowParticipantText = new TextField();
    private Label callSheetLabel = new Label("Call Sheet: ");
    private TextField callSheetText = new TextField();
    private Label iobLabel = new Label("IOB: ");
    private TextField iobText = new TextField();
    private Label mosLabel = new Label("MOS: ");
    private TextField mosText = new TextField();
    private Label fofLabel = new Label("FOF: ");
    private TextField fofText = new TextField();
    private Label fnoLabel = new Label("FNO: ");
    private TextField fnoText = new TextField();
    private Label classidLabel = new Label("Class ID: ");
    private TextField classidText = new TextField();
    private Label countLabel = new Label("");

    private OptionGroup updateGroup = new OptionGroup("", updateList);
    private OptionGroup fundGroup = new OptionGroup("", fundList);
    private OptionGroup mutualFundGroup = new OptionGroup("", mutualFundList);
    private OptionGroup filterGroup = new OptionGroup("", filterList);

    private Collection<ComplexModuleData> complexes;
    private BeanItemContainer<ComplexModuleData> container;
    private Grid complexGrid;
    private List<ComplexFund> completeFunds;
    private Map<Integer, ComplexFund> complexFundMap = Maps.newHashMap();

    protected DateTime sixWeek;
    protected int selectedComplex;
    protected int selectedContact;
    protected String selectedDate;
    protected int selectedFundid;
    protected ComplexModuleData selectedRow;

    private boolean tableEditable;
    private HashMap<Integer, TnaValidator> tnaValidators;
    private HashMap<Integer, NavValidator> navValidators;

    private TextField[][]
 arrowGrid;

    private boolean isSuper = false;
    private boolean isAdmin = false;
    private boolean isRegular = false;
    private boolean isReadOnly = false;

    private Object itemID;


    private Object manageItemId(Object itemIdentifier) {

        if (itemIdentifier != null) {
            this.itemID = itemIdentifier;
        }

        return this.itemID;
    }

    @Inject
    public ComplexGridModule(final WeeklyDAO dao) {
        this.dao = dao;
        this.setId("ComplexGridModule");
        tableEditable = true;
        tnaValidators = new HashMap<>();
        navValidators = new HashMap<>();

        VerticalLayout content = new VerticalLayout();
        this.setContent(content);

        complexes = new ArrayList<>();
        container = new BeanItemContainer<>(ComplexModuleData.class, complexes);
        complexGrid = new Grid(container);

        complexGrid.setSelectionMode(Grid.SelectionMode.SINGLE);
        complexGrid.setImmediate(true);
        complexGrid.setEditorEnabled(true);
        complexGrid.setEditorBuffered(false);

        complexGrid.setWidth("1180px");
        complexGrid.setHeightByRows(11);

        complexGrid.setColumnOrder("ct", "fundid", "ticker", "fundname", "tna", "tnac", "nav", "navc", "shares", "sharesc", "nncf");

        complexGrid.getColumn("ct").setHeaderCaption("#");
        complexGrid.getColumn("ct").setRenderer(new NumberRenderer(new DecimalFormat("#")));
        complexGrid.getColumn("fundid").setHeaderCaption("Fund ID");
        complexGrid.getColumn("fundid").setRenderer(new NumberRenderer(new DecimalFormat("#")));
        complexGrid.getColumn("ticker").setHeaderCaption("Ticker");
        complexGrid.getColumn("fundname").setHeaderCaption("Fund Name");


        TextField navEditField = new TextField();
        navEditField.addFocusListener(new FieldEvents.FocusListener() {
            @Override
            public void focus(FieldEvents.FocusEvent event) {

                System.out.println("==========> FOCUS NAV ");

                navEditField.selectAll();
            }
        });

        navEditField.addShortcutListener(
                new AbstractField.FocusShortcut(navEditField, ShortcutAction.KeyCode.ENTER, null) {

                    @Override
                    public void handleAction(Object sender, Object target) {

                        Object targetParent = ((AbstractComponent) target).getParent();

                        if (complexGrid.isEditorActive() && !(targetParent instanceof VerticalLayout)) {
                            try {
                                complexGrid.saveEditor();
                                complexGrid.cancelEditor();
                                complexGrid.focus();
                            } catch (FieldGroup.CommitException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                });

        TextField tnaEditField = new TextField();
        tnaEditField.addFocusListener(new FieldEvents.FocusListener() {
            @Override
            public void focus(FieldEvents.FocusEvent event) {
                tnaEditField.selectAll();
            }
        });

        tnaEditField.addShortcutListener(
                new AbstractField.FocusShortcut(tnaEditField, ShortcutAction.KeyCode.ENTER, null) {

                    @Override
                    public void handleAction(Object sender, Object target) {

                        if (target == null) {
                            return;
                        }

                        Object targetParent = ((AbstractComponent) target).getParent();

                        if (complexGrid.isEditorActive() && !(targetParent instanceof VerticalLayout)) {
                            try {
                                complexGrid.saveEditor();
                                complexGrid.cancelEditor();
                                complexGrid.focus();
                            } catch (FieldGroup.CommitException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                });


        TextField sharesEditField = new TextField();

        sharesEditField.setNullRepresentation("");


        sharesEditField.addFocusListener(new FieldEvents.FocusListener() {
            @Override
            public void focus(FieldEvents.FocusEvent event) {
                sharesEditField.selectAll();
            }
        });

        sharesEditField.addShortcutListener(
                new AbstractField.FocusShortcut(sharesEditField, ShortcutAction.KeyCode.ENTER, null) {

                    @Override
                    public void handleAction(Object sender, Object target) {

                        Object targetParent = ((AbstractComponent) target).getParent();

                        if (complexGrid.isEditorActive() && !(targetParent instanceof VerticalLayout)) {
                            try {
                                complexGrid.saveEditor();
                                complexGrid.cancelEditor();
                                complexGrid.focus();
                            } catch (FieldGroup.CommitException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                });


        complexGrid.addBlurListener(new FieldEvents.BlurListener() {

            private String getNavConfirm(String navc, String valid) {
                String buttonValue = navc.equals("") ? "n" : "y";
                if (valid.equals("y") && buttonValue.equals("n"))
                    return null;
                return buttonValue;
            }

            private String getTnaConfirm(String tnac, String valid) {
                String buttonValue = tnac.equals("") ? "n" : "y";
                if (valid.equals("y") && buttonValue.equals("n"))
                    return null;
                return buttonValue;
            }

            private String getValidNav(BigDecimal nav, BigDecimal oldNav) {
                int nn = (nav == null ? 0 : nav.intValue());
                int on = (oldNav == null ? 0 : oldNav.intValue());

                // NOTE: If you change the logic here, make sure to change the logic in the NavValidator
                if (on == 0) {
                    return "n";
                } else if ((nn - on) / on >= .05) {
                    return "n";
                } else if (nn == on) {
                    return "n";
                }
                return "y";
            }

            private String getValidTna(BigDecimal tna, BigDecimal oldTna) {
                int nt = (tna == null ? 0 : tna.intValue());
                int ot = (oldTna == null ? 0 : oldTna.intValue());

                // NOTE: If you change the logic here, make sure to change the logic in the TnaValidator
                if (ot == 0) {
                    return "n";
                } else if (Math.abs(nt - ot) >= 7500) {
                    return "n";
                } else if (Math.abs((nt - ot) / ot) >= .15) {
                    return "n";
                } else if (nt == ot && nt >= 1000) {
                    return "n";
                }
                return "y";
            }

            @Override
            public void blur(FieldEvents.BlurEvent blurEvent) {

                complexGrid.select(manageItemId(complexGrid.getEditedItemId()));
                Object obj = complexGrid.getSelectedRow();

                if (obj != null && obj instanceof ComplexModuleData) {

                    ComplexModuleData moduleData = (ComplexModuleData) obj;

//                    final TextField field = (TextField) blurEvent.getComponent();
//                    final String txtValue = field.getValue().trim();
//                    final int value = Util.toInt(txtValue);
//                    final BigDecimal bigValue = new BigDecimal(value);

                    final String username = (String) getSession().getAttribute("user");
                    final BigDecimal shares = moduleData.getShares();
                    final BigDecimal tna = moduleData.getTna();
                    final BigDecimal nav = moduleData.getNav();
                    final String tnac = moduleData.getTnac();
                    final String navc = moduleData.getNavc();
                    final BigDecimal oldTna = moduleData.getTnaold();
                    final BigDecimal oldNav = moduleData.getNavold();
                    final String validTna = getValidTna(tna, oldTna);
                    final String validNav = getValidNav(nav, oldNav);
                    final int classtype = moduleData.getClasstype();
                    final int fundid = moduleData.getFundid();
                    final UI ui = getUI();

                    dao.insertUpdateTnaValue(selectedDate, fundid, tna, validTna, getTnaConfirm(tnac, validTna), classtype, username);
                    App.EVENT_BUS.post(new FundUpdateEvent(getSession().getSession().getId(), fundid, selectedDate));

                    dao.insertUpdateNavValue(selectedDate, fundid, nav, validNav, getNavConfirm(navc, validNav), username);
                    App.EVENT_BUS.post(new FundUpdateEvent(getSession().getSession().getId(), fundid, selectedDate));

                    dao.insertUpdateSharesValue(selectedDate, fundid, shares, username);
                    App.EVENT_BUS.post(new FundUpdateEvent(getSession().getSession().getId(), fundid, selectedDate));

                }
            }

        });


        complexGrid.getColumn("tna").setHeaderCaption("TNA");
        complexGrid.getColumn("tnac").setHeaderCaption("TC");
        complexGrid.getColumn("nav").setHeaderCaption("NAV");
        complexGrid.getColumn("navc").setHeaderCaption("NC");
        complexGrid.getColumn("shares").setHeaderCaption("Shares");
        complexGrid.getColumn("sharesc").setHeaderCaption("SC");
        complexGrid.getColumn("nncf").setHeaderCaption("NNCF");

        complexGrid.getColumn("ct").setEditable(false);
        complexGrid.getColumn("fundid").setEditable(false);
        complexGrid.getColumn("ticker").setEditable(false);
        complexGrid.getColumn("fundname").setEditable(false);

        complexGrid.getColumn("tna").setEditable(true);
        complexGrid.getColumn("nav").setEditable(true);
        complexGrid.getColumn("shares").setEditable(true);

        complexGrid.getColumn("ct").setWidth(60);
        complexGrid.getColumn("fundid").setWidth(75);
        complexGrid.getColumn("ticker").setWidth(100);
        complexGrid.getColumn("fundname").setWidth(385);
        complexGrid.getColumn("tna").setWidth(140);

        complexGrid.getColumn("tnac").setWidth(40);
        complexGrid.getColumn("nav").setWidth(140);
        complexGrid.getColumn("navc").setWidth(40);
        complexGrid.getColumn("shares").setWidth(140);
        complexGrid.getColumn("sharesc").setWidth(40);
        complexGrid.getColumn("nncf").setWidth(140);


//        complexGrid.removeColumn("nncf");

        complexGrid.removeColumn("tnaold");
        complexGrid.removeColumn("navold");
        complexGrid.removeColumn("sharesold");
        complexGrid.removeColumn("tnaDescription");
        complexGrid.removeColumn("navDescription");
        complexGrid.removeColumn("sharesDescription");
        complexGrid.removeColumn("classtype");
        complexGrid.removeColumn("iob");
        complexGrid.removeColumn("fof");
        complexGrid.removeColumn("tna_source");
        complexGrid.removeColumn("tna_entry_user");
        complexGrid.removeColumn("tna_entry_date");
        complexGrid.removeColumn("tna_update_user");
        complexGrid.removeColumn("tna_update_date");
        complexGrid.removeColumn("nav_source");
        complexGrid.removeColumn("nav_entry_user");
        complexGrid.removeColumn("nav_entry_date");
        complexGrid.removeColumn("nav_update_user");
        complexGrid.removeColumn("nav_update_date");
        complexGrid.removeColumn("shares_source");
        complexGrid.removeColumn("shares_entry_user");
        complexGrid.removeColumn("shares_entry_date");
        complexGrid.removeColumn("shares_update_user");
        complexGrid.removeColumn("shares_update_date");

        complexGrid.addItemClickListener(new ItemClickEvent.ItemClickListener() {
            @Override
            public void itemClick(ItemClickEvent itemClickEvent) {
                Object currentItemId = itemClickEvent.getItemId();
                // FIXME
//                rowFundClicked(Util.toInt(currentItemId.toString()));
            }
        });

        complexGrid.addFocusListener(new FieldEvents.FocusListener() {
            @Override
            public void focus(FieldEvents.FocusEvent focusEvent) {
                Object obj = complexGrid.getSelectedRow();

                if (obj != null && obj instanceof ComplexModuleData) {
                    rowFundClicked((ComplexModuleData) obj);
                } else {
                    rowFundClicked(null);
                }

                complexGrid.select(complexGrid.getId());
            }
        });


        complexGrid.addBlurListener(new FieldEvents.BlurListener() {
            @Override
            public void blur(FieldEvents.BlurEvent blurEvent) {

                Object obj = complexGrid.getSelectedRow();

                if (obj != null && obj instanceof ComplexModuleData) {
                    rowFundClicked((ComplexModuleData) obj);
                } else {
                    rowFundClicked(null);
                }

                complexGrid.select(complexGrid.getId());
            }
        });

        complexGrid.addSelectionListener(new SelectionEvent.SelectionListener() {
            @Override
            public void select(SelectionEvent selectionEvent) {
                Object obj = complexGrid.getSelectedRow();

                if (obj != null && obj instanceof ComplexModuleData) {
                    rowFundClicked((ComplexModuleData) obj);
                } else {
                    rowFundClicked(null);
                }
            }
        });


        complexNameLabel.setWidth("130");
        complexNameText.setWidth("500");
        complexNameText.setEnabled(false);
        flowParticipantLabel.setWidth("130");
        flowParticipantText.setWidth("50");
        flowParticipantText.setEnabled(false);
        callSheetLabel.setWidth("80");
        callSheetText.setWidth("50");
        callSheetText.setEnabled(false);
        iobText.setEnabled(false);
        iobLabel.setWidth("100");
        iobText.setWidth("50");
        mosText.setEnabled(false);
        mosLabel.setWidth("80");
        mosText.setWidth("50");
        fofText.setEnabled(false);
        fofLabel.setWidth("50");
        fofText.setWidth("50");
        fofText.setEnabled(false);
        fnoLabel.setWidth("50");
        fnoText.setWidth("100");
        fnoText.setEnabled(false);
        classidLabel.setWidth("80");
        classidText.setWidth("50");
        classidText.setEnabled(false);

        GridLayout complexLayout = new GridLayout(10, 3);
        complexLayout.addComponent(complexNameLabel, 0, 0);
        complexLayout.addComponent(complexNameText, 1, 0, 9, 0);
        complexLayout.addComponent(flowParticipantLabel, 0, 1);
        complexLayout.addComponent(flowParticipantText, 1, 1);
        complexLayout.addComponent(callSheetLabel, 2, 1);
        complexLayout.addComponent(callSheetText, 3, 1);
        complexLayout.addComponent(iobLabel, 0, 2);
        complexLayout.addComponent(iobText, 1, 2);
        complexLayout.addComponent(mosLabel, 2, 2);
        complexLayout.addComponent(mosText, 3, 2);
        complexLayout.addComponent(fofLabel, 4, 2);
        complexLayout.addComponent(fofText, 5, 2);
        complexLayout.addComponent(fnoLabel, 6, 2);
        complexLayout.addComponent(fnoText, 7, 2);
        complexLayout.addComponent(classidLabel, 8, 2);
        complexLayout.addComponent(classidText, 9, 2);

        updateGroup.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                tableEditable = updateGroup.getValue().equals(UPDATEABLE);
                updateTablesEditability();
                sentUpdateMessage();
            }
        });
        updateGroup.setValue(UPDATEABLE);

        fundGroup.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                selectedFundid = 0;
                if (fundGroup.getValue().equals(ETF) || fundGroup.getValue().equals(BOTH))
                    mutualFundGroup.setValue(BOTH);
                applyFundsToTable();
                clearPanelInfo();
                clearFundLevelInfo();
            }
        });
        fundGroup.setValue(MUTUAL);

        mutualFundGroup.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                selectedFundid = 0;
                applyFundsToTable();
                clearPanelInfo();
                clearFundLevelInfo();
            }
        });
        mutualFundGroup.setValue(BOTH);

        filterGroup.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                selectedFundid = 0;
                applyFundsToTable();
                clearPanelInfo();
                clearFundLevelInfo();
            }
        });
        filterGroup.setValue(FILTERED);

        GridLayout filterLayout = new GridLayout(4, 2);

        filterLayout.addComponent(updateGroup, 0, 1);
        filterLayout.addComponent(fundGroup, 1, 1);
        filterLayout.addComponent(mutualFundGroup, 2, 1);
        filterLayout.addComponent(filterGroup, 3, 1);

        HorizontalLayout topLayout = new HorizontalLayout();
        topLayout.addStyleName("padding-five");
        topLayout.setWidth("1150px");
        topLayout.addComponent(complexLayout);
        topLayout.setComponentAlignment(complexLayout, Alignment.MIDDLE_LEFT);
        topLayout.addComponent(filterLayout);
        topLayout.setComponentAlignment(filterLayout, Alignment.MIDDLE_RIGHT);

        countLabel.addStyleName("padding-five");
        countLabel.addStyleName("bold-font");

        content.addComponent(topLayout);


        complexGrid.setCellStyleGenerator(cellRef -> {// Java 8

            int tna;
            float nav;


            ComplexModuleData d = (ComplexModuleData) cellRef.getItemId();

            boolean etf = d.getClasstype() == 5;

            String style = null;

//            System.out.println("====> Style " + cellRef.getPropertyId() + "=====> '" + cellRef.getValue() + "' ===> '" + d.getTnaold() + "' =====> '" + d.getNavold() + "'");

            if ("tna".equals(cellRef.getPropertyId())) {

                try {
                    tna = cellRef.getValue() == null ? 0 : Util.removeCommas(cellRef.getValue().toString()).intValue();

                    TnaValidatorGrid tnaVal;

                    tnaVal = new TnaValidatorGrid(d.getTnaold() == null ? 0 : d.getTnaold().intValue());

                    if (!tnaVal.isValid(tna))
                        style = "custom-style supercell";
                    else
                        style = "custom-style";
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if ("nav".equals(cellRef.getPropertyId())) {

                try {
                    nav = cellRef.getValue() == null ? 0 : Float.parseFloat(cellRef.getValue().toString());

                    NavValidatorGrid navVal;

                    navVal = new NavValidatorGrid(d.getNavold() == null ? 0 : d.getNavold().floatValue(), etf);

                    if (!navVal.isValid(nav))
                        style = "custom-style supercell";
                    else
                        style = "custom-style";
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else
                style = null;

            return style;
        });


        complexGrid.addShortcutListener(new ShortcutListener("DOWN",
                ShortcutAction.KeyCode.ARROW_DOWN, null) {
            @Override
            public void handleAction(Object sender, Object target) {
                if (target == null) {
                    return;
                }

//                logger.info("----> DOWN KEY <----");
                Object targetParent = ((AbstractComponent) target).getParent();
                if ((targetParent != null) && (targetParent instanceof Grid)) {
                    Grid targetGrid = (Grid) targetParent;

                    if (targetGrid.isEditorActive()) {
                        try {
                            targetGrid.saveEditor();
                            targetGrid.cancelEditor();
                            targetGrid.focus();

                            complexGrid.getColumn("tna").setEditorField(tnaEditField);
                            complexGrid.getColumn("nav").setEditorField(navEditField);
                            complexGrid.getColumn("shares").setEditorField(sharesEditField);

                        } catch (FieldGroup.CommitException e) {
                            Notification.show("Validation failed");
                        }
                    }
                }
            }
        });


        complexGrid.addShortcutListener(new ShortcutListener("UP",
                ShortcutAction.KeyCode.ARROW_UP, null) {
            @Override
            public void handleAction(Object sender, Object target) {
                if (target == null) {
                    return;
                }

//                logger.info("----> UP KEY <----");


                Object targetParent = ((AbstractComponent) target).getParent();
                if ((targetParent != null) && (targetParent instanceof Grid)) {
                    Grid targetGrid = (Grid) targetParent;

                    if (targetGrid.isEditorActive()) {
                        try {
                            targetGrid.saveEditor();
                            targetGrid.cancelEditor();
                            targetGrid.focus();

                            complexGrid.getColumn("tna").setEditorField(tnaEditField);
                            complexGrid.getColumn("nav").setEditorField(navEditField);
                            complexGrid.getColumn("shares").setEditorField(sharesEditField);

                        } catch (FieldGroup.CommitException e) {
                            Notification.show("Validation failed");
                        }
                    }
                }
            }
        });

        /* ------------------- BEGIN TEST ALL LISTENERS ------------------------- */

//        complexGrid.addListener(new Property.ValueChangeListener(){
//
//            @Override
//            public void valueChange(Field.ValueChangeEvent event)
//            {
//                System.out.println("------> please work");
//            }
//        });

//        complexGrid.addSortListener(new SortEvent.SortListener() {
//            @Override
//            public void sort(SortEvent sortEvent) {
//                logger.info("----> SORT LISTENER <----");
//            }
//        });
//        complexGrid.addColumnReorderListener(new Grid.ColumnReorderListener() {
//            @Override
//            public void columnReorder(Grid.ColumnReorderEvent columnReorderEvent) {
//                logger.info("----> COLUMN REORDER LISTENER <----");
//            }
//        });
//        complexGrid.addColumnVisibilityChangeListener(new Grid.ColumnVisibilityChangeListener() {
//            @Override
//            public void columnVisibilityChanged(Grid.ColumnVisibilityChangeEvent columnVisibilityChangeEvent) {
//                logger.info("----> COLUMN VISIBILITY LISTENER <----");
//            }
//        });
//        complexGrid.addSelectionListener(new SelectionEvent.SelectionListener() {
//            @Override
//            public void select(SelectionEvent selectionEvent) {
//                logger.info("----> SELECTION LISTENER <----");
//            }
//        });
//        complexGrid.addItemClickListener(new ItemClickEvent.ItemClickListener() {
//            @Override
//            public void itemClick(ItemClickEvent itemClickEvent) {
//                logger.info("----> ITEM CLICK LISTENER <----");
//            }
//        });
//        complexGrid.addBlurListener(new FieldEvents.BlurListener() {
//            @Override
//            public void blur(FieldEvents.BlurEvent blurEvent) {
//                logger.info("----> BLUR LISTENER <----");
//            }
//        });
//
//        complexGrid.addAttachListener(new AttachListener() {
//            @Override
//            public void attach(AttachEvent attachEvent) {
//                logger.info("----> ATTACH LISTENER <----");
//            }
//        });
//        complexGrid.addDetachListener(new DetachListener() {
//            @Override
//            public void detach(DetachEvent detachEvent) {
//                logger.info("----> DETACH LISTENER <----");
//            }
//        });
//
//        complexGrid.addEditorListener(new Grid.EditorListener() {
//            @Override
//            public void editorOpened(Grid.EditorOpenEvent editorOpenEvent) {
//                logger.info("---> OPENED <---");
//            }
//
//            @Override
//            public void editorMoved(Grid.EditorMoveEvent editorMoveEvent) {
//                logger.info("---> MOVED <---");
//            }
//
//            @Override
//            public void editorClosed(Grid.EditorCloseEvent editorCloseEvent) {
//                logger.info("---> CLOSED <---");
//            }
//        });

        /* ------------------- END TEST ALL LISTENERS ------------------------- */


        /* ------------------- BUTTON SECTION FOR TNA NAV AND SHARES -------------- */

        complexGrid.getColumn("tnac")
                .setRenderer(new ButtonRenderer(e -> { // Java 8

                    ComplexModuleData d = (ComplexModuleData) e.getItemId();

                    complexGrid.select(manageItemId(e.getItemId()));

                    if (complexGrid.isEnabled()) {
                        final ConfirmationWindow results = new ConfirmationWindow(dao, ConfirmationWindow.TNA_TYPE, d.getFundid(), selectedDate, d.getIob(), d.getClasstype());
                        UI.getCurrent().addWindow(results);
                        results.addFocusListener(new FieldEvents.FocusListener() {
                            @Override
                            public void focus(FieldEvents.FocusEvent focusEvent) {
                                results.grabFocus();
                            }
                        });
                    }

                }));

        complexGrid.getColumn("navc")
                .setRenderer(new ButtonRenderer(e -> {// Java 8

                    ComplexModuleData d = (ComplexModuleData) e.getItemId();

                    complexGrid.select(manageItemId(e.getItemId()));

                    if (complexGrid.isEnabled()) {
                        final ConfirmationWindow results = new ConfirmationWindow(dao, ConfirmationWindow.NAV_TYPE, d.getFundid(), selectedDate, d.getIob(), d.getClasstype());
                        UI.getCurrent().addWindow(results);
                        results.addFocusListener(new FieldEvents.FocusListener() {
                            @Override
                            public void focus(FieldEvents.FocusEvent focusEvent) {
                                results.grabFocus();
                            }
                        });
                    }
                }));


        complexGrid.getColumn("sharesc")
                .setRenderer(new ButtonRenderer(e -> {// Java 8

                    ComplexModuleData d = (ComplexModuleData) e.getItemId();

                    complexGrid.select(manageItemId(e.getItemId()));

                    if (complexGrid.isEnabled()) {
                        final ConfirmationWindow results = new ConfirmationWindow(dao, ConfirmationWindow.SHARES_TYPE, d.getFundid(), selectedDate, d.getIob(), d.getClasstype());
                        UI.getCurrent().addWindow(results);
                        results.addFocusListener(new FieldEvents.FocusListener() {
                            @Override
                            public void focus(FieldEvents.FocusEvent focusEvent) {
                                results.grabFocus();
                            }
                        });
                    }
                }));

        content.addComponent(complexGrid);
        content.addComponent(countLabel);

        App.EVENT_BUS.register(this);
    }


    private void sentUpdateMessage() {
        if (getSession() != null && getSession().getSession() != null && updateGroup != null)
            App.EVENT_BUS.post(new ScreenUpdatableEvent(getSession().getSession().getId(), updateGroup.getValue().equals(UPDATEABLE)));
    }

    @Subscribe
    public void fundChange(FundUpdateEvent event) {
        try {
            if (getSession() == null || getSession().getSession() == null)
                return;
            String sessionID = getSession().getSession().getId();
            if (!sessionID.equals(event.getSessionID()))
                return;

            if (!event.getDate().equals(selectedDate))
                return;

            ComplexFund workingFund = null;
            // update the completeFunds list
            for (int i = 0; i < completeFunds.size(); i++) {
                ComplexFund fund = completeFunds.get(i);
                if (fund.getFundid() == event.getFundid()) {
                    List<ComplexFund> funds = dao.selectComplexFundByFundidDate(fund.getFundid(), selectedDate, fund.getClasstype());
                    if (funds.size() > 0) {
                        fund = funds.get(0);
                        workingFund = fund;
                        completeFunds.set(i, fund);
                    }
                }
            }

            // update the table values for update user/date
            Item row = complexGrid.getContainerDataSource().getItem(event.getFundid());
            if (row != null && workingFund != null) {
                ((Label) row.getItemProperty("tna_update_user").getValue()).setValue(workingFund.getTna_update_user());
                ((Label) row.getItemProperty("tna_update_date").getValue()).setValue(workingFund.getTna_update_date());
                ((Label) row.getItemProperty("nav_update_user").getValue()).setValue(workingFund.getNav_update_user());
                ((Label) row.getItemProperty("nav_update_date").getValue()).setValue(workingFund.getNav_update_date());
                ((Label) row.getItemProperty("shares_update_user").getValue()).setValue(workingFund.getShares_update_user());
                ((Label) row.getItemProperty("shares_update_date").getValue()).setValue(workingFund.getShares_update_date());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe
    public void confirmationChange(ConfirmationEvent event) {
        try {
            if (getSession() == null || getSession().getSession() == null)
                return;
            String sessionID = getSession().getSession().getId();
            if (!sessionID.equals(event.getSessionID()))
                return;

            Item row = complexGrid.getContainerDataSource().getItem(event.getFundid());
            if (row == null)
                return;

            switch (event.getType()) {
                case ConfirmationWindow.TNA_TYPE:
                    Button tnaBtn = (Button) row.getItemProperty("tnac").getValue();
                    TextField tnaField = (TextField) row.getItemProperty("tna").getValue();
                    tnaBtn.setCaption(event.getValue());
                    tnaBtn.setDescription(event.getDescription());

                    // Get old validator, remove the listener then set a new listner
                    String tnaOldStr = ((Label) row.getItemProperty("tnaold").getValue()).getValue();
                    TnaValidator oldTnaValidator = tnaValidators.get(event.getFundid());
                    tnaField.removeValidator(oldTnaValidator);
                    TnaValidator newTnaValidator = new TnaValidator(Util.toInt(tnaOldStr), tnaBtn);
                    tnaField.addValidator(newTnaValidator);

                    // now, remove the old validator from the list, and add a new one
                    tnaValidators.remove(event.getFundid());
                    tnaValidators.put(event.getFundid(), newTnaValidator);
                    break;
                case ConfirmationWindow.NAV_TYPE:
                    Button navBtn = (Button) row.getItemProperty("navc").getValue();
                    TextField navField = (TextField) row.getItemProperty("nav").getValue();
                    navBtn.setCaption(event.getValue());
                    navBtn.setDescription(event.getDescription());

                    // Get old validator, remove the listener then set a new listner
                    String navOldStr = ((Label) row.getItemProperty("navold").getValue()).getValue();
                    NavValidator oldNavValidator = navValidators.get(event.getFundid());
                    navField.removeValidator(oldNavValidator);
                    NavValidator newNavValidator = new NavValidator(Util.toFloat(navOldStr), navBtn, false);
                    navField.addValidator(newNavValidator);

                    // now, remove the old validator from the list, and add a new one
                    navValidators.remove(event.getFundid());
                    navValidators.put(event.getFundid(), newNavValidator);
                    break;
                case ConfirmationWindow.SHARES_TYPE:
                    ((Button) row.getItemProperty("sharesc").getValue()).setCaption(event.getValue());
                    ((Button) row.getItemProperty("sharesc").getValue()).setDescription(event.getDescription());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe
    public void dateChange(WeeklyDateComplexEvent event) {
        try {
            if (getSession() == null || getSession().getSession() == null)
                return;
            String sessionID = getSession().getSession().getId();
            if (!sessionID.equals(event.getSessionID()))
                return;

            selectedDate = event.getDate();
            completeFunds = null;
            complexGrid.getContainerDataSource().removeAllItems();
            selectedComplex = 0;
            selectedContact = 0;
            selectedRow = null;
            setPermissions();
            List<ComplexLookup> lkup = dao.getComplexLookup(event.getComplex());
            if (lkup.size() > 0) {
                ComplexLookup complex = lkup.get(0);
                complexNameText.setValue(complex.getName());
                flowParticipantText.setValue(complex.getFlowParticipant());
                callSheetText.setValue(complex.getCallSheet());
                clearFundLevelInfo();
            } else {
                complexNameText.setValue("");
                flowParticipantText.setValue("");
                callSheetText.setValue("");
                clearFundLevelInfo();
            }
            updateRowCount();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clearFundLevelInfo() {
        iobText.setValue("");
        mosText.setValue("");
        fofText.setValue("");
        fnoText.setValue("");
        classidText.setValue("");
    }

    private void clearPanelInfo() {
        if (getSession() == null || getSession().getSession() == null)
            return;
        App.EVENT_BUS.post(new WeeklyFundSelectionEvent(getSession().getSession().getId(), 0, null, null, null, 0,
                0, "", "", "", "",
                0, "", "", "", "",
                0, "", "", "", ""));
    }

    protected void updateComplexFundMap() {
        complexFundMap.clear();
        for (ComplexFund fund : completeFunds) {
            complexFundMap.put(fund.getFundid(), fund);
        }
    }

    @Subscribe
    public void autoContactChange(SelectComplexFundEvent event) {
        try {
            if (getSession() == null || getSession().getSession() == null)
                return;
            String sessionID = getSession().getSession().getId();
            if (!sessionID.equals(event.getSessionID()))
                return;

            completeFunds = null;
            selectedRow = null;

            String date = event.getDate();
            int complex = event.getComplex();
            int contact = event.getCntno();

            if (complex != selectedComplex || contact != selectedContact || !date.equals(selectedDate)) {
                selectedComplex = complex;
                selectedDate = date;
                selectedContact = contact;
                String old_date = dao.getPreviousDate(selectedDate);

                try {
                    if (contact == 0)
                        completeFunds = dao.selectComplexFundsWithNoContact(complex, date, old_date);
                    else
                        completeFunds = dao.selectComplexFundsByContact(complex, contact, date, old_date);

                    applyFundsToTable();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//            complexGrid.select(event.getFundid());
            // FIXME
//            complexGrid.setCurrentPageFirstItemId(event.getFundid());
//            rowFundClicked(event.getFundid());
            updateRowCount();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe
    public void contactChange(WeeklyComplexFundEvent event) {
        try {
            if (getSession() == null || getSession().getSession() == null)
                return;
            String sessionID = getSession().getSession().getId();
            if (!sessionID.equals(event.getSessionID()))
                return;

            completeFunds = null;
            selectedRow = null;
            String date = event.getDate();
            int complex = event.getComplex();
            int contact = event.getCntno();

            if (complex != selectedComplex || contact != selectedContact || !date.equals(selectedDate)) {
                selectedComplex = complex;
                selectedDate = date;
                selectedContact = contact;
                String old_date = dao.getPreviousDate(selectedDate);

                if (contact == 0)
                    completeFunds = dao.selectComplexFundsWithNoContact(complex, date, old_date);
                else
                    completeFunds = dao.selectComplexFundsByContact(complex, contact, date, old_date);

                applyFundsToTable();
            }
            updateRowCount();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateTablesEditability() {

        if (complexGrid.isEditorActive()) {
            try {
                complexGrid.cancelEditor();
                complexGrid.saveEditor();
                complexGrid.focus();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        tableEditable = updateGroup.getValue().equals(UPDATEABLE);

        complexGrid.setEditorEnabled(tableEditable);
        complexGrid.setEditorBuffered(false);
    }

    private void rowFundClicked(ComplexModuleData row) {
        selectedRow = row;
        if (row != null) {
            int fundid = row.getFundid();
            int classtype = 0;//row.getClasstype();

            BigDecimal tna = null;//row.getTna();
            BigDecimal nav = null;//row.getNav();
            BigDecimal shares = null;//row.getShares();

            Object tna_source = row.getTna_source();
            Object tna_entry_user = row.getTna_entry_user();
            Object tna_entry_date = row.getTna_entry_date();
            Object tna_update_user = row.getTna_update_user();
            Object tna_update_date = row.getTna_update_date();
            Object nav_source = row.getNav_source();
            Object nav_entry_user = row.getNav_entry_user();
            Object nav_entry_date = row.getNav_entry_date();
            Object nav_update_user = row.getNav_update_user();
            Object nav_update_date = row.getNav_update_date();
            Object shares_source = row.getShares_source();
            Object shares_entry_user = row.getShares_entry_user();
            Object shares_entry_date = row.getShares_entry_date();
            Object shares_update_user = row.getShares_update_user();
            Object shares_update_date = row.getShares_update_date();

            App.EVENT_BUS.post(new WeeklyFundSelectionEvent(getSession().getSession().getId(), fundid, tna, nav, shares, classtype,
                    tna_source, tna_entry_user, tna_entry_date, tna_update_user, tna_update_date,
                    nav_source, nav_entry_user, nav_entry_date, nav_update_user, nav_update_date,
                    shares_source, shares_entry_user, shares_entry_date, shares_update_user, shares_update_date));

            String[] imf = dao.getIobMosFofFnoClass(fundid, classtype, selectedDate);
            iobText.setValue(imf[0]
);
            mosText.setValue(imf[1]
);
            fofText.setValue(imf[2]
);
            fnoText.setValue(imf[3]
);
            classidText.setValue(imf[4]
);
        }

        updateRowCount();
    }

    private void updateRowCount() {
        int count = selectedRow == null ? 0 : selectedRow.getCt();
        int size = complexGrid.getContainerDataSource().getItemIds() == null ? 0 : complexGrid.getContainerDataSource().getItemIds().size();
        countLabel.setValue("Fund " + count + " of " + size);
    }

    private List<ComplexFund> filterFunds() {
        if (completeFunds == null || completeFunds.size() == 0)
            return null;

        Predicate<ComplexFund> isETF = new Predicate<ComplexFund>() {
            @Override
            public boolean apply(ComplexFund value) {
                return value.getClasstype() == 5;
            }
        };
        Predicate<ComplexFund> isNotETF = new Predicate<ComplexFund>() {
            @Override
            public boolean apply(ComplexFund value) {
                return value.getClasstype() != 5;
            }
        };
        Predicate<ComplexFund> isMMKT = new Predicate<ComplexFund>() {
            @Override
            public boolean apply(ComplexFund value) {
                return value.getIob12() >= 40;
            }
        };
        Predicate<ComplexFund> isConvent = new Predicate<ComplexFund>() {
            @Override
            public boolean apply(ComplexFund value) {
                return value.getIob12() < 40;
            }
        };
        Predicate<ComplexFund> isFiltered = new Predicate<ComplexFund>() {
            @Override
            public boolean apply(ComplexFund value) {
                boolean n = false;
                boolean t = false;
                boolean s = false;
                if (value.getNavv() != null && value.getNavv().equalsIgnoreCase("y"))
                    n = true;
                if (value.getTnav() != null && value.getTnav().equalsIgnoreCase("y"))
                    t = true;
                if (value.getSharesv() != null && value.getSharesv().equalsIgnoreCase("y"))
                    s = true;
                return n || t || s;
            }
        };

        Iterable<ComplexFund> workingFunds;

        if (fundGroup.getValue().equals(ETF))
            workingFunds = Iterables.filter(completeFunds, isETF);
        else if (fundGroup.getValue().equals(MUTUAL))
            workingFunds = Iterables.filter(completeFunds, isNotETF);
        else
            workingFunds = completeFunds;

        if (mutualFundGroup.getValue().equals(MMKT))
            workingFunds = Iterables.filter(workingFunds, isMMKT);
        else if (mutualFundGroup.getValue().equals(CONVENT))
            workingFunds = Iterables.filter(workingFunds, isConvent);

        if (mutualFundGroup.getValue().equals(FILTERED))
            workingFunds = Iterables.filter(workingFunds, isFiltered);

        if (workingFunds == null)
            return null;

        List<ComplexFund> retval = new ArrayList<>();
        for (ComplexFund cf : workingFunds) {
            retval.add(cf);
        }

        return retval;
    }

    private void applyFundsToTable() {
        if (getSession() == null)
            return;

        List<ComplexFund> funds = filterFunds();
        complexGrid.getContainerDataSource().removeAllItems();
        boolean applyFilter = filterGroup.getValue().equals(FILTERED);

        if (funds != null) {
            arrowGrid = new TextField[funds.size()]
[4]
;
            int ct = 0;
            for (final ComplexFund f : funds) {

                boolean etf = f.getClasstype() == 5;

                BigDecimal bigOldTna = f.getOld_tna();
                int oldTna = 0;
                if (bigOldTna != null)
                    oldTna = bigOldTna.intValue();
                TnaValidatorGrid tnaVal = new TnaValidatorGrid(oldTna);

                BigDecimal bigOldNav = f.getOld_nav();
                float oldNav = 0;
                if (bigOldNav != null)
                    oldNav = bigOldNav.floatValue();
                NavValidatorGrid navVal = new NavValidatorGrid(oldNav, etf);

                if (applyFilter) {
                    boolean filter = true;

                    // If TNA is blank or an invalid TNA
                    if (f.getTnaBigDecimal() == null || !tnaVal.isValid(f.getTnaBigDecimal().intValue()))
                        filter = false;
                        // If TNA confirmation has data
                    else if (f.getTna_text() != null && !f.getTna_text().equals(""))
                        filter = false;
                        // if its not an ETF and no NAV or invalid NAV
                    else if (!etf && (f.getNavBigDecimal() == null || !navVal.isValid(f.getNavBigDecimal().floatValue())))
                        filter = false;
                        // if its not an ETF and NAV confirmation has data
                    else if (!etf && f.getNav_text() != null && !f.getNav_text().equals(""))
                        filter = false;
                        // if ETF and shares are blank
                    else if (etf && f.getSharesBigDecimal() == null)
                        filter = false;

                    if (filter)
                        continue;
                }

                ComplexModuleData item = new ComplexModuleData();

                item.setTna(f.getTnaBigDecimal());
                item.setTnac(f.getTnac());
                item.setTnaDescription(f.getTna_text());
                item.setTnaold(f.getOld_tna());


                item.setNav(f.getNavBigDecimal());
                item.setNavc(f.getNavc());
                item.setNavDescription(f.getNav_text());
                item.setNavold(f.getOld_nav());

                item.setShares(f.getSharesBigDecimal());
                item.setSharesc(f.getSharesc());
                item.setSharesDescription(f.getShares_text());
                item.setSharesold(f.getOld_shares());

                item.setNncf(f.getNncf());

                item.setCt(++ct);
                item.setFundid(f.getFundid());
                item.setTicker(f.getTicker());
                item.setFundname(f.getName());
                item.setClasstype(f.getClasstype());
                item.setIob(f.getIob12());
                item.setFof(f.getFof());

                item.setTna_source(f.getTna_source());
                item.setTna_entry_user(f.getTna_entry_user());
                item.setTna_entry_date(f.getTna_entry_date());
                item.setTna_update_user(f.getTna_update_user());
                item.setTna_update_date(f.getTna_update_date());
                item.setNav_source(f.getNav_source());
                item.setNav_entry_user(f.getNav_entry_user());
                item.setNav_entry_date(f.getNav_entry_date());
                item.setNav_update_user(f.getNav_update_user());
                item.setNav_update_date(f.getNav_update_date());
                item.setShares_source(f.getShares_source());
                item.setShares_entry_user(f.getShares_entry_user());
                item.setShares_entry_date(f.getShares_entry_date());
                item.setShares_update_user(f.getShares_update_user());
                item.setShares_update_date(f.getShares_update_date());

                complexes.add(item);
            }
        }

        container = new BeanItemContainer<>(ComplexModuleData.class, complexes);
        complexGrid.setContainerDataSource(container);

        updateRowCount();
    }

    public void setPermissions() {
        if (sixWeek == null)
            sixWeek = dao.getSixWeekDate();

        String security = (String) getSession().getAttribute("security");
        isSuper = false;
        isAdmin = false;
        isRegular = false;
        isReadOnly = false;

        if (security.equals(WeeklySecurityUtils.WEEKLY_SUPER)) {
            isSuper = true;
        } else if (security.equals(WeeklySecurityUtils.WEEKLY_ADMIN)) {
            isAdmin = true;
        } else if (security.equals(WeeklySecurityUtils.WEEKLY_REGULAR)) {
            isRegular = true;
        } else {
            isReadOnly = true;
        }

        if (isReadOnly || (isRegular && Util.greaterThanSixWeeks(selectedDate, sixWeek))) {
            updateGroup.setValue(VIEW_ONLY);
            updateGroup.setEnabled(false);
        } else {
            updateGroup.setValue(UPDATEABLE);
            updateGroup.setEnabled(true);
        }
    }


    private void cursorUp(Object target) {
        for (int i = 0; i < arrowGrid.length; i++) {
            for (int j = 0; j < arrowGrid[i]
.length; j++) {
                if (arrowGrid[i]
[j]
 == target) {
                    for (int k = i - 1; k >= 0; k--) {
                        if (arrowGrid[k]
[j]
 != null && arrowGrid[k]
[j]
.isVisible()) {
                            arrowGrid[k]
[j]
.focus();
                            return;
                        }
                    }
                }
            }
        }
    }

    private void cursorDown(Object target) {
        for (int i = 0; i < arrowGrid.length; i++) {
            for (int j = 0; j < arrowGrid[i]
.length; j++) {
                if (arrowGrid[i]
[j]
 == target) {
                    for (int k = i + 1; k < arrowGrid.length; k++) {
                        if (arrowGrid[k]
[j]
 != null && arrowGrid[k]
[j]
.isVisible()) {
                            arrowGrid[k]
[j]
.focus();
                            return;
                        }
                    }
                }
            }
        }
    }

    private void cursorLeft(Object target) {
        // If we are moving left, just grab focus of TNA ... nothing more to do
        for (int i = 0; i < arrowGrid.length; i++) {
            for (int j = 0; j < arrowGrid[i]
.length; j++) {
                if (arrowGrid[i]
[j]
 == target) {
                    if (j == 1) {
                        arrowGrid[i]
[0]
.focus();
                    } else if (j == 2) {
                        if (arrowGrid[i]
[1]
 != null && arrowGrid[i]
[1]
.isEnabled())
                            arrowGrid[i]
[1]
.focus();
                        else
                            arrowGrid[i]
[0]
.focus();
                    } else {
                        if (arrowGrid[i]
[2]
 != null && arrowGrid[i]
[2]
.isEnabled())
                            arrowGrid[i]
[2]
.focus();
                        else if (arrowGrid[i]
[1]
 != null && arrowGrid[i]
[1]
.isEnabled())
                            arrowGrid[i]
[1]
.focus();
                        else
                            arrowGrid[i]
[0]
.focus();
                    }
                }
            }
        }
    }

    private void cursorRight(Object target) {
        for (int i = 0; i < arrowGrid.length; i++) {
            for (int j = 0; j < arrowGrid[i]
.length; j++) {
                if (arrowGrid[i]
[j]
 == target) {
                    if (j == 0) {
                        if (arrowGrid[i]
[1]
 != null)
                            arrowGrid[i]
[1]
.focus();
                        else
                            arrowGrid[i]
[2]
.focus();
                        return;
                    } else if (j == 1) {
                        if (arrowGrid[i]
[2]
 != null && arrowGrid[i]
[2]
.isEnabled())
                            arrowGrid[i]
[2]
.focus();
                        else if (arrowGrid[i]
[3]
 != null && arrowGrid[i]
[3]
.isEnabled() && arrowGrid[i]
[3]
.isVisible())
                            arrowGrid[i]
[3]
.focus();
                        return;
                    } else if (j == 2) {
                        if (arrowGrid[i]
[3]
 != null && arrowGrid[i]
[3]
.isEnabled() && arrowGrid[i]
[3]
.isVisible())
                            arrowGrid[i]
[3]
.focus();
                        return;
                    }
                }
            }
        }
    }

    private ShortcutListener upShortCut = new ShortcutListener("Up", ShortcutAction.KeyCode.ARROW_UP, null) {
        @Override
        public void handleAction(Object sender, Object target) {
            cursorUp(target);
        }
    };
    private ShortcutListener downShortCut = new ShortcutListener("Down", ShortcutAction.KeyCode.ARROW_DOWN, null) {
        @Override
        public void handleAction(Object sender, Object target) {
            cursorDown(target);
        }
    };
    private ShortcutListener leftShortCut = new ShortcutListener("Left", ShortcutAction.KeyCode.ARROW_LEFT, null) {
        @Override
        public void handleAction(Object sender, Object target) {
            cursorLeft(target);
        }
    };
    private ShortcutListener rightShortCut = new ShortcutListener("Right", ShortcutAction.KeyCode.ARROW_RIGHT, null) {
        @Override
        public void handleAction(Object sender, Object target) {
            cursorRight(target);
        }
    };


    @Override
    public void enter(ViewChangeListener.ViewChangeEvent viewChangeEvent) {

    }
}

So … it seems this was my fault entirely. It is a bug in my code. It is now fixed, sorry for the trouble.