Example usage for java.util ArrayList indexOf

List of usage examples for java.util ArrayList indexOf

Introduction

In this page you can find the example usage for java.util ArrayList indexOf.

Prototype

public int indexOf(Object o) 

Source Link

Document

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Usage

From source file:com.digium.respoke.ContactManager.java

public void joinGroup(final String groupName, final Respoke.TaskCompletionListener completionListener) {
    if (null != sharedClient) {
        ArrayList<String> groupsToJoin = new ArrayList<String>();
        groupsToJoin.add(groupName);//from   w w w .jav a2 s .  c o  m

        sharedClient.joinGroups(groupsToJoin, new RespokeClient.JoinGroupCompletionListener() {
            @Override
            public void onSuccess(final ArrayList<RespokeGroup> groupList) {
                Log.d(TAG, "Group joined, fetching member list");

                // This demo app will only ever join one group at a time, so just grab the first entry
                final RespokeGroup group = groupList.get(0);
                group.setListener(ContactManager.this);
                groups.add(group);

                // Establish the connection and endpoint tracking arrays for this group
                groupConnectionArrays.put(groupName, new ArrayList<RespokeConnection>());

                final ArrayList<RespokeEndpoint> groupEndpoints = new ArrayList<RespokeEndpoint>();
                groupEndpointArrays.put(groupName, groupEndpoints);

                // Start tracking the conversation with this group
                Conversation groupConversation = new Conversation(groupName);
                groupConversations.put(groupName, groupConversation);

                group.getMembers(new RespokeGroup.GetGroupMembersCompletionListener() {
                    @Override
                    public void onSuccess(ArrayList<RespokeConnection> memberArray) {
                        groupConnectionArrays.put(groupName, new ArrayList<RespokeConnection>(memberArray));

                        // Evaluate each connection in the new group
                        for (RespokeConnection each : memberArray) {
                            // Find the endpoint to which the connection belongs
                            RespokeEndpoint parentEndpoint = each.getEndpoint();

                            trackEndpoint(parentEndpoint);

                            // If this endpoint is not known in this specific group, remember it
                            if (-1 == groupEndpoints.indexOf(parentEndpoint)) {
                                groupEndpoints.add(parentEndpoint);
                            }
                        }

                        // Notify any UI listeners that group membership has changed
                        Intent intent = new Intent(GROUP_MEMBERSHIP_CHANGED);
                        intent.putExtra("groupID", group.getGroupID());
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                        completionListener.onSuccess();
                    }

                    @Override
                    public void onError(String errorMessage) {
                        completionListener.onError(errorMessage);
                    }
                });
            }

            @Override
            public void onError(String errorMessage) {
                completionListener.onError(errorMessage);
            }
        });
    }
}

From source file:com.clust4j.algo.MeanShift.java

@Override
protected MeanShift fit() {
    synchronized (fitLock) {

        if (null != labels) // Already fit this model
            return this;

        // Put the results into a Map (hash because tree imposes comparable casting)
        final LogTimer timer = new LogTimer();
        centroids = new ArrayList<double[]>();

        /*/*from   ww w. j ava  2 s.  c  o  m*/
         * Get the neighborhoods and center intensity object. Will iterate until
         * either the centers are found, or the max try count is exceeded. For each
         * iteration, will increase bandwidth.
         */
        RadiusNeighbors nbrs = new RadiusNeighbors(this, bandwidth).fit();

        // Compute the seeds and center intensity
        // If parallelism is permitted, try it. 
        CenterIntensity intensity = null;
        if (parallel) {
            try {
                intensity = new ParallelCenterIntensity(nbrs);
            } catch (RejectedExecutionException e) {
                // Shouldn't happen...
                warn("parallel search failed; falling back to serial");
            }
        }

        // Gets here if serial or if parallel failed...
        if (null == intensity)
            intensity = new SerialCenterIntensity(nbrs);

        // Check for points all too far from seeds
        if (intensity.isEmpty()) {
            error(new IllegalClusterStateException("No point " + "was within bandwidth=" + bandwidth
                    + " of any seed; try increasing bandwidth"));
        } else {
            converged = true;
            itersElapsed = intensity.getIters(); // max iters elapsed
        }

        // Extract the centroids
        int idx = 0, m_prime = intensity.size();
        final Array2DRowRealMatrix sorted_centers = new Array2DRowRealMatrix(m_prime, n);

        for (MeanShiftSeed entry : intensity)
            sorted_centers.setRow(idx++, entry.getPair().getKey());

        // Fit the new neighbors model
        nbrs = new RadiusNeighbors(sorted_centers, new RadiusNeighborsParameters(bandwidth)
                .setSeed(this.random_state).setMetric(this.dist_metric).setForceParallel(parallel), true).fit();

        // Post-processing. Remove near duplicate seeds
        // If dist btwn two kernels is less than bandwidth, remove one w fewer pts
        // Create a boolean mask, init true
        final boolean[] unique = new boolean[m_prime];
        for (int i = 0; i < unique.length; i++)
            unique[i] = true;

        // Pre-filtered summaries...
        ArrayList<SummaryLite> allSummary = intensity.getSummaries();

        // Iterate over sorted centers and query radii
        int redundant_ct = 0;
        int[] indcs;
        double[] center;
        for (int i = 0; i < m_prime; i++) {
            if (unique[i]) {
                center = sorted_centers.getRow(i);
                indcs = nbrs.getNeighbors(new double[][] { center }, bandwidth, false).getIndices()[0];

                for (int id : indcs)
                    unique[id] = false;

                unique[i] = true; // Keep this as true
            }
        }

        // Now assign the centroids...
        SummaryLite summ;
        for (int i = 0; i < unique.length; i++) {
            summ = allSummary.get(i);

            if (unique[i]) {
                summ.retained = true;
                centroids.add(sorted_centers.getRow(i));
            }

            fitSummary.add(summ.toArray());
        }

        // calc redundant ct
        redundant_ct = unique.length - centroids.size();

        // also put the centroids into a matrix. We have to
        // wait to perform this op, because we have to know
        // the size of centroids first...
        Array2DRowRealMatrix centers = new Array2DRowRealMatrix(centroids.size(), n);
        for (int i = 0; i < centroids.size(); i++)
            centers.setRow(i, centroids.get(i));

        // Build yet another neighbors model...
        NearestNeighbors nn = new NearestNeighbors(centers, new NearestNeighborsParameters(1)
                .setSeed(this.random_state).setMetric(this.dist_metric).setForceParallel(false), true).fit();

        info((numClusters = centroids.size()) + " optimal kernel" + (numClusters != 1 ? "s" : "")
                + " identified");
        info(redundant_ct + " nearly-identical kernel" + (redundant_ct != 1 ? "s" : "") + " removed");

        // Get the nearest...
        final LogTimer clustTimer = new LogTimer();
        Neighborhood knrst = nn.getNeighbors(data.getDataRef());
        labels = MatUtils.flatten(knrst.getIndices());

        // order the labels..
        /* 
         * Reduce labels to a sorted, gapless, list
         * sklearn line: cluster_centers_indices = np.unique(labels)
         */
        ArrayList<Integer> centroidIndices = new ArrayList<Integer>(numClusters);
        for (Integer i : labels) // force autobox
            if (!centroidIndices.contains(i)) // Not race condition because synchronized
                centroidIndices.add(i);

        /*
         * final label assignment...
         * sklearn line: labels = np.searchsorted(cluster_centers_indices, labels)
         */
        for (int i = 0; i < labels.length; i++)
            labels[i] = centroidIndices.indexOf(labels[i]);

        // Wrap up...
        // Count missing
        numNoisey = 0;
        for (int lab : labels)
            if (lab == NOISE_CLASS)
                numNoisey++;
        info(numNoisey + " record" + (numNoisey != 1 ? "s" : "") + " classified noise");

        info("completed cluster labeling in " + clustTimer.toString());

        sayBye(timer);
        return this;
    }

}

From source file:oscar.eform.data.EForm.java

public void setOpenerValues(ArrayList<String> names, ArrayList<String> values) {
    StringBuilder html = new StringBuilder(this.formHtml);
    EFormLoader.getInstance();/*from   w  w  w.j a  v  a  2s .c o m*/
    String opener = EFormLoader.getOpener(); // default: opener: "oscarOPEN="
    int markerLoc = -1;
    while ((markerLoc = getFieldIndex(html, markerLoc + 1)) >= 0) {
        String fieldHeader = getFieldHeader(html, markerLoc);
        if (EFormUtil.blank(EFormUtil.getAttribute(opener, fieldHeader)))
            continue;

        String fieldName = EFormUtil.removeQuotes(EFormUtil.getAttribute("name", fieldHeader));
        int i;
        if (EFormUtil.blank(fieldName))
            continue;
        if ((i = names.indexOf(fieldName)) < 0)
            continue;
        if (EFormUtil.blank(values.get(i)))
            continue;

        // sets up the pointer where to write the value
        int pointer = nextSpot(html, markerLoc + EFormUtil.getAttributePos(opener, fieldHeader));
        int offset = EFormUtil.getAttributePos(OPENER_VALUE, fieldHeader);
        if (offset >= 0) {
            //delete current OPENER_VALUE
            pointer = markerLoc + offset;
            int valueEnd = nextSpot(html, pointer);
            html.delete(pointer - 1, valueEnd);
        }
        html = putValue(values.get(i), OPENER_VALUE, pointer, html);
    }
    formHtml = html.toString();
}

From source file:org.matrix.console.fragments.MembersInvitationDialogFragment.java

/**
 * Init the dialog view.//ww  w.  ja v  a  2  s . c  o  m
 * @param v the dialog view.
 */
void initView(View v) {
    mListView = ((ListView) v.findViewById(R.id.listView_members));

    IMXStore store = mSession.getDataHandler().getStore();

    // remove the current room members
    ArrayList<String> idsToIgnore = new ArrayList<String>();
    Room fromRoom = store.getRoom(mRoomId);
    Collection<RoomMember> currentMembers = fromRoom.getMembers();

    for (RoomMember member : currentMembers) {
        idsToIgnore.add(member.getUserId());
    }

    // get the members list
    ArrayList<RoomMember> members_OneToOne = new ArrayList<RoomMember>();
    ArrayList<String> ids_OneToOne = new ArrayList<String>();

    ArrayList<RoomMember> members_MaxTenMembers = new ArrayList<RoomMember>();
    ArrayList<String> ids_MaxTenMembers = new ArrayList<String>();

    ArrayList<RoomMember> members_BigRooms = new ArrayList<RoomMember>();
    ArrayList<String> ids_BigRooms = new ArrayList<String>();

    Collection<RoomSummary> summaries = store.getSummaries();

    for (RoomSummary summary : summaries) {
        // not the current summary
        if (!summary.getRoomId().equals(mRoomId)) {
            Room curRoom = store.getRoom(summary.getRoomId());
            Collection<RoomMember> otherRoomMembers = curRoom.getMembers();

            for (RoomMember member : otherRoomMembers) {
                String userID = member.getUserId();

                // accepted User ID or still active users
                if ((idsToIgnore.indexOf(userID) < 0)
                        && (RoomMember.MEMBERSHIP_JOIN.equals(member.membership))) {
                    int posOneToOne = ids_OneToOne.indexOf(userID);
                    int posTenMembers = ids_MaxTenMembers.indexOf(userID);
                    int posBigRooms = ids_BigRooms.indexOf(userID);

                    if (otherRoomMembers.size() <= 2) {
                        if (posBigRooms >= 0) {
                            members_BigRooms.remove(posBigRooms);
                            ids_BigRooms.remove(posBigRooms);
                        }

                        if (posTenMembers >= 0) {
                            members_MaxTenMembers.remove(posTenMembers);
                            ids_MaxTenMembers.remove(posTenMembers);
                        }

                        if (posOneToOne < 0) {
                            members_OneToOne.add(member);
                            ids_OneToOne.add(member.getUserId());
                        }
                    } else if (otherRoomMembers.size() <= 10) {
                        if (posBigRooms >= 0) {
                            members_BigRooms.remove(posBigRooms);
                            ids_BigRooms.remove(posBigRooms);
                        }

                        if ((posTenMembers < 0) && (posOneToOne < 0)) {
                            members_MaxTenMembers.add(member);
                            ids_MaxTenMembers.add(member.getUserId());
                        }
                    } else {
                        if ((posBigRooms < 0) && (posTenMembers < 0) && (posOneToOne < 0)) {
                            members_BigRooms.add(member);
                            ids_BigRooms.add(member.getUserId());
                        }
                    }
                }
            }
        }
    }

    mAdapter = new MembersInvitationAdapter(getActivity(), mSession.getHomeserverConfig(),
            R.layout.adapter_item_members_invitation, getMXMediasCache());

    Collections.sort(members_OneToOne, alphaComparator);
    Collections.sort(members_MaxTenMembers, alphaComparator);
    Collections.sort(members_BigRooms, alphaComparator);

    mAdapter.addAll(members_OneToOne);
    mAdapter.addAll(members_MaxTenMembers);
    mAdapter.addAll(members_BigRooms);

    ArrayList<Integer> bounds = new ArrayList<Integer>();
    ArrayList<String> sectionTitles = new ArrayList<String>();

    int index = 0;

    if (members_OneToOne.size() > 0) {
        bounds.add(index);
        sectionTitles.add(getActivity().getResources().getString(R.string.members_one_to_one));
        index += members_OneToOne.size();
    }

    if (members_MaxTenMembers.size() > 0) {
        bounds.add(index);
        sectionTitles.add(getActivity().getResources().getString(R.string.members_small_room_members));
        index += members_MaxTenMembers.size();
    }

    if (members_BigRooms.size() > 0) {
        bounds.add(index);
        sectionTitles.add(getActivity().getResources().getString(R.string.members_large_room_members));
        index += members_BigRooms.size();
    }

    mAdapter.setSectionTiles(bounds, sectionTitles);

    mListView.setAdapter(mAdapter);
}

From source file:com.vgi.mafscaling.VECalc.java

private boolean getColumnsFilters(String[] elements) {
    boolean ret = true;
    ArrayList<String> columns = new ArrayList<String>(Arrays.asList(elements));
    String logClOlStatusColName = Config.getClOlStatusColumnName();
    String logThrottleAngleColName = Config.getThrottleAngleColumnName();
    String logFfbColName = Config.getFinalFuelingBaseColumnName();
    String logSdColName = Config.getVEFlowColumnName();
    String logWbAfrColName = Config.getWidebandAfrColumnName();
    String logStockAfrColName = Config.getAfrColumnName();
    String logAfLearningColName = Config.getAfLearningColumnName();
    String logAfCorrectionColName = Config.getAfCorrectionColumnName();
    String logRpmColName = Config.getRpmColumnName();
    String logMafColName = Config.getMassAirflowColumnName();
    String logIatColName = Config.getIatColumnName();
    String logMpColName = Config.getMpColumnName();
    isOl = Config.veOpenLoop();/*ww w. ja v a 2  s.c o  m*/
    logClOlStatusColIdx = columns.indexOf(logClOlStatusColName);
    logThrottleAngleColIdx = columns.indexOf(logThrottleAngleColName);
    logFfbColIdx = columns.indexOf(logFfbColName);
    logSdColIdx = columns.indexOf(logSdColName);
    logWbAfrColIdx = columns.indexOf(logWbAfrColName);
    logStockAfrColIdx = columns.indexOf(logStockAfrColName);
    logAfLearningColIdx = columns.indexOf(logAfLearningColName);
    logAfCorrectionColIdx = columns.indexOf(logAfCorrectionColName);
    logRpmColIdx = columns.indexOf(logRpmColName);
    logMafColIdx = columns.indexOf(logMafColName);
    logIatColIdx = columns.indexOf(logIatColName);
    logMpColIdx = columns.indexOf(logMpColName);
    if (logThrottleAngleColIdx == -1) {
        Config.setThrottleAngleColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logFfbColIdx == -1) {
        Config.setFinalFuelingBaseColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logSdColIdx == -1) {
        Config.setVEFlowColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logWbAfrColIdx == -1 && isOl) {
        Config.setWidebandAfrColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logStockAfrColIdx == -1 && !isOl) {
        Config.setAfrColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logAfLearningColIdx == -1 && !isOl) {
        Config.setAfLearningColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logAfCorrectionColIdx == -1 && !isOl) {
        Config.setAfCorrectionColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logRpmColIdx == -1) {
        Config.setRpmColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logMafColIdx == -1) {
        Config.setMassAirflowColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logMpColIdx == -1) {
        Config.setMpColumnName(Config.NO_NAME);
        ret = false;
    }
    if (logIatColIdx == -1) {
        Config.setIatColumnName(Config.NO_NAME);
        ret = false;
    }
    clValue = Config.getVEClOlStatusValue();
    rpmMin = Config.getVERPMMinimumValue();
    mpMin = Config.getVEMPMinimumValue();
    iatMax = Config.getVEIatMaximumValue();
    ffbMax = Config.getFFBMaximumValue();
    ffbMin = Config.getFFBMinimumValue();
    thrtlMaxChange = Config.getVEThrottleChangeMaxValue();
    minCellHitCount = Config.getVEMinCellHitCount();
    thrtlMin = Config.getVEThrottleMinimumValue();
    afrMax = (isOl ? Config.getVEOlAfrMaximumValue() : Config.getVEClAfrMaximumValue());
    afrMin = Config.getVEAfrMinimumValue();
    afrRowOffset = Config.getWBO2RowOffset();
    corrApplied = Config.getVECorrectionAppliedValue();
    return ret;
}

From source file:SimpleGui.QueryGenerator.java

/**
 * Internal private function to be used in create subquery sequences- that creates in all ascending combinations
 * @param str/*from  ww w.  j a  v a 2  s  . c  om*/
 * @param singleSequencesList
 * @return
 */
private boolean isAscendingOrder(String str, ArrayList<String> singleSequencesList) {
    String[] sampleStr = str.split(Pattern.quote(")"));
    for (int i = 0; i < sampleStr.length - 1; i++) {
        for (int j = i; j < sampleStr.length; j++) {
            String sample1 = sampleStr[i];
            sample1 = sample1.substring(1, sample1.length());
            String sample2 = sampleStr[j];
            sample2 = sample2.substring(1, sample2.length());

            if (singleSequencesList.indexOf(sample1) > singleSequencesList.indexOf(sample2))
                return false;

        }

    }
    return true;
}

From source file:com.globalsight.everest.webapp.pagehandler.edit.online.EditorPageHandler.java

private void previousPage(EditorState p_state, HttpSession p_session, boolean p_fromActivity)
        throws EnvoyServletException {
    ArrayList<EditorState.PagePair> pages = p_state.getPages();
    pages = (ArrayList<PagePair>) getPagePairList(p_session, pages);
    int i_index = pages.indexOf(p_state.getCurrentPage());

    if (p_fromActivity) {
        boolean foundNonempty = false;
        boolean allEmptyBefore = true;
        while (i_index > 0) {
            --i_index;//w ww.  jav a 2s  .c o m
            EditorState.PagePair pp = (EditorState.PagePair) pages.get(i_index);

            if (!foundNonempty) {
                p_state.setCurrentPage(pp);
                p_state.setIsFirstPage(i_index == 0);
                p_state.setIsLastPage(false);

                initState(p_state, p_session);

                if (p_state.getUserIsPm() && s_pmCanEditTargetPages) {
                    if (EditorHelper.pmCanEditCurrentPage(p_state)) {
                        p_state.setReadOnly(false);
                        p_state.setAllowEditAll(true);
                        p_state.setEditAllState(EDIT_ALL);
                    } else {
                        p_state.setReadOnly(true);
                    }
                }
                foundNonempty = true;
                continue;
            }

            if (foundNonempty && allEmptyBefore) {
                allEmptyBefore = false;
                break;
            }

        }
        if (foundNonempty && allEmptyBefore) {
            p_state.setIsFirstPage(true);
        }
    } else {
        if (i_index > 0) {
            --i_index;

            p_state.setCurrentPage((EditorState.PagePair) pages.get(i_index));

            p_state.setIsFirstPage(i_index == 0);
            p_state.setIsLastPage(false);

            initState(p_state, p_session);

            if (p_state.getUserIsPm() && s_pmCanEditTargetPages) {
                if (EditorHelper.pmCanEditCurrentPage(p_state)) {
                    p_state.setReadOnly(false);
                    p_state.setAllowEditAll(true);
                    p_state.setEditAllState(EDIT_ALL);
                } else {
                    p_state.setReadOnly(true);
                }
            }
        }
    }

}

From source file:com.globalsight.everest.webapp.pagehandler.edit.online.EditorPageHandler.java

private void nextPage(EditorState p_state, HttpSession p_session, boolean p_fromActivity)
        throws EnvoyServletException {
    ArrayList<EditorState.PagePair> pages = p_state.getPages();
    pages = (ArrayList<PagePair>) getPagePairList(p_session, pages);
    int i_index = pages.indexOf(p_state.getCurrentPage());

    if (p_fromActivity) {
        boolean foundNonempty = false;
        boolean allEmptyAfter = true;

        while (i_index >= 0 && i_index < (pages.size() - 1)) {
            ++i_index;/* w ww  .  ja  v a2 s . c  o  m*/

            EditorState.PagePair pp = (EditorState.PagePair) pages.get(i_index);

            if (!foundNonempty) {
                p_state.setCurrentPage(pp);
                p_state.setIsFirstPage(false);
                p_state.setIsLastPage(i_index == (pages.size() - 1));

                initState(p_state, p_session);

                if (p_state.getUserIsPm() && s_pmCanEditTargetPages) {
                    if (EditorHelper.pmCanEditCurrentPage(p_state)) {
                        p_state.setReadOnly(false);
                        p_state.setAllowEditAll(true);
                        p_state.setEditAllState(EDIT_ALL);
                    } else {
                        p_state.setReadOnly(true);
                    }
                }
                foundNonempty = true;
                continue;
            }

            if (foundNonempty && allEmptyAfter) {
                allEmptyAfter = false;
                break;
            }

        }
        if (foundNonempty && allEmptyAfter) {
            p_state.setIsLastPage(true);
        }
    }

    else {
        if (i_index >= 0 && i_index < (pages.size() - 1)) {
            ++i_index;

            p_state.setCurrentPage((EditorState.PagePair) pages.get(i_index));

            p_state.setIsFirstPage(false);
            p_state.setIsLastPage(i_index == (pages.size() - 1));

            initState(p_state, p_session);

            if (p_state.getUserIsPm() && s_pmCanEditTargetPages) {
                if (EditorHelper.pmCanEditCurrentPage(p_state)) {
                    p_state.setReadOnly(false);
                    p_state.setAllowEditAll(true);
                    p_state.setEditAllState(EDIT_ALL);
                } else {
                    p_state.setReadOnly(true);
                }
            }
        }
    }

}

From source file:org.ut.biolab.medsavant.client.view.component.SearchableTablePanel.java

public SearchableTablePanel(String pageName, String[] columnNames, Class[] columnClasses, int[] hiddenColumns,
        boolean allowSearch, boolean allowSort, int defaultRows, boolean allowPages,
        TableSelectionType selectionType, int defaultRowsRetrieved, DataRetriever<Object[]> retriever) {

    this.pageName = pageName;
    this.rowsPerPageX = defaultRows;
    this.defaultRowsRetrieved = defaultRowsRetrieved;

    this.retriever = retriever;
    this.hiddenColumns = hiddenColumns;
    table = new SortableTable() {
        @Override/*from www  .  jav a 2  s  . co m*/
        public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
            synchronized (SearchableTablePanel.this) {
                JComponent comp = (JComponent) super.prepareRenderer(renderer, row, col);

                // Even index, selected or not selected
                if (isRowToggled(TableModelWrapperUtils.getActualRowAt(this.getSortableTableModel(), row))) { //this.getActualRowAt(this.getSortedRowAt(row)))) {
                    comp.setBackground(new Color(178, 225, 92));
                } else if (isCellSelected(row, col)) {
                    //comp.setBackground(new Color(75, 149, 229));
                    comp.setBackground(SELECTED_COLOUR);
                } else if (selectedRows != null
                        && selectedRows.contains(TableModelWrapperUtils.getActualRowAt(getModel(), row))) {
                    //comp.setBackground(SELECTED_COLOUR);
                } else if (row % 2 == 0 && !isCellSelected(row, col)) {
                    comp.setBackground(Color.WHITE);
                } else {
                    comp.setBackground(DARK_COLOUR);
                }

                comp.setBorder(BorderFactory.createEmptyBorder(0, 7, 0, 7));
                return comp;
            }
        }

        @Override
        public String getToolTipText(MouseEvent e) {
            return getToolTip(
                    TableModelWrapperUtils.getActualRowAt(table.getModel(), table.rowAtPoint(e.getPoint())));
        }
    };

    table.setToolTipText(""); //necessary to force check for tooltip text

    table.setClearSelectionOnTableDataChanges(true);
    table.setOptimized(true);
    table.setColumnAutoResizable(true);
    table.setAutoResort(false);
    table.setRowHeight(20);
    table.setSortable(allowSort);
    table.setSortingEnabled(allowSort);
    table.setFocusable(selectionType != TableSelectionType.DISABLED);
    //table.setCellSelectionEnabled(allowSelection);
    table.setCellSelectionEnabled(selectionType == TableSelectionType.CELL);
    table.setRowSelectionAllowed(selectionType == TableSelectionType.ROW);

    table.setAutoResizeMode(SortableTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

    //column chooser
    TableHeaderPopupMenuInstaller installer = new TableHeaderPopupMenuInstaller(table);
    installer.addTableHeaderPopupMenuCustomizer(new AutoResizePopupMenuCustomizer());
    columnChooser = new ColumnChooser(table);
    installer.addTableHeaderPopupMenuCustomizer(columnChooser);

    AutoFilterTableHeader header = new AutoFilterTableHeader(table);
    header.setAutoFilterEnabled(true);
    header.setShowFilterIcon(true);
    header.setShowFilterName(true);
    table.setTableHeader(header);

    filterField = new QuickTableFilterField(model);

    if (allowPages) {
        filterField.setHintText("Search for anything on the page");
    } else {
        filterField.setHintText("Search for anything");
    }

    setLayout(new BorderLayout(3, 3));
    fieldPanel = ViewUtil.getClearPanel();

    if (allowSearch) {
        fieldPanel.add(filterField);
    }

    chooseColumnButton = new JButton("Columns");
    chooseColumnButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            columnChooser.showDialog();
        }
    });

    helpButton = ViewUtil.getHelpButton("About Variant List",
            "Variants are sorted first by DNA ID, then by position.  The list of variants within each page can be sorted by various fields by clicking the corresponding column name, but note that this will only sort the current page.");
    exportButton = new JButton("Export");
    exportButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            try {
                ExportTable.exportTable(table);
            } catch (Exception ex) {
                LOG.error("Error while exporting.", ex);
                DialogUtils.displayException("MedSavant",
                        "<HTML>A problem occurred while exporting.<BR>Make sure the output file is not already in use.</HTML>",
                        ex);
            }
        }
    });

    fieldPanel.add(helpButton);
    fieldPanel.add(chooseColumnButton);
    fieldPanel.add(exportButton);

    bottomPanel = ViewUtil.getClearPanel();
    bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));

    gotoFirst = niceButton();
    gotoPrevious = niceButton();
    gotoNext = niceButton();
    gotoLast = niceButton();

    gotoFirst.setIcon(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.FIRST));
    gotoPrevious.setIcon(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.PREVIOUS));
    gotoNext.setIcon(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.NEXT));
    gotoLast.setIcon(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.LAST));

    gotoFirst.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            goToFirstPage();
        }
    });
    gotoPrevious.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            goToPreviousPage();
        }
    });
    gotoNext.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            goToNextPage();
        }
    });
    gotoLast.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            goToLastPage();
        }
    });

    pageText = new JTextField();
    ViewUtil.makeSmall(pageText);
    pageText.setColumns(5);
    pageText.setMaximumSize(new Dimension(50, 20));
    pageText.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_ENTER) {
                try {
                    setPageNumber(Integer.parseInt(pageText.getText()));
                } catch (NumberFormatException ex) {
                    setPageNumber(0);
                }
            }
        }
    });

    amountLabel = new JLabel();
    ViewUtil.makeSmall(amountLabel);
    bottomPanel.add(amountLabel);

    pageLabel1 = new JLabel("Page ");
    ViewUtil.makeSmall(pageLabel1);
    pageLabel2 = new JLabel();
    ViewUtil.makeSmall(pageLabel2);

    bottomPanel.add(Box.createHorizontalGlue());
    bottomPanel.add(gotoFirst);
    bottomPanel.add(gotoPrevious);
    strut(bottomPanel);
    bottomPanel.add(pageLabel1);
    bottomPanel.add(pageText);
    bottomPanel.add(pageLabel2);
    strut(bottomPanel);
    bottomPanel.add(gotoNext);
    bottomPanel.add(gotoLast);
    bottomPanel.add(Box.createHorizontalGlue());

    strut(bottomPanel);

    JLabel perpageL = new JLabel("Per page:");
    ViewUtil.makeSmall(perpageL);
    bottomPanel.add(perpageL);

    strut(bottomPanel);

    boolean hasDefaultRowsPerPage = true;
    if (rowsPerPageX == ROWSPERPAGE_1 || rowsPerPageX == ROWSPERPAGE_2 || rowsPerPageX == ROWSPERPAGE_3) {
        hasDefaultRowsPerPage = false;
    }
    ArrayList<Integer> rowsList = new ArrayList<Integer>();
    rowsList.add(ROWSPERPAGE_1);
    rowsList.add(ROWSPERPAGE_2);
    rowsList.add(ROWSPERPAGE_3);
    Integer[] finalList = new Integer[3];
    if (hasDefaultRowsPerPage) {
        rowsList.add(rowsPerPageX);
        Collections.sort(rowsList);
    }
    finalList = rowsList.toArray(finalList);

    rowsPerPageDropdown = new JComboBox(finalList);
    ViewUtil.makeSmall(rowsPerPageDropdown);
    rowsPerPageDropdown.setPrototypeDisplayValue(ROWSPERPAGE_3);
    if (hasDefaultRowsPerPage) {
        rowsPerPageDropdown.setSelectedIndex(rowsList.indexOf(rowsPerPageX));
    } else {
        rowsPerPageDropdown.setSelectedIndex(1);
    }
    rowsPerPageDropdown.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox) e.getSource();
            int rowsPerPage = (Integer) cb.getSelectedItem();
            setNumRowsPerPage(rowsPerPage);
        }
    });
    rowsPerPageDropdown.setPreferredSize(new Dimension(100, 25));
    rowsPerPageDropdown.setMaximumSize(new Dimension(100, 25));
    bottomPanel.add(rowsPerPageDropdown);

    setTableModel(data, columnNames, columnClasses);

    JPanel tablePanel = new JPanel(new BorderLayout(3, 3));
    JScrollPane jsp = new JScrollPane(table);
    jsp.setBorder(null);
    tablePanel.add(jsp);

    if (allowSort) {
        add(fieldPanel, BorderLayout.NORTH);
    }

    if (allowPages) {
        add(bottomPanel, BorderLayout.SOUTH);
    }

    add(tablePanel, BorderLayout.CENTER);

    initEmpty();
}

From source file:com.ichi2.libanki.test.SchedTestCase.java

@MediumTest
public void test_deckTree() {
    Collection d = Shared.getEmptyDeck(getInstrumentation().getContext());
    assertNotNull(d);/*from   ww  w .  j  a v a2s  .c  o m*/
    d.getDecks().id("new::b::c");
    d.getDecks().id("new2");
    // new should not appear twice in tree
    ArrayList<String> names = new ArrayList<String>();
    TreeSet<Object[]> tree = d.getSched().deckDueTree(Sched.DECK_INFORMATION_SIMPLE_COUNTS);
    for (Object[] n : tree) {
        names.add(((String[]) n[0])[((String[]) n[0]).length - 1]);
    }
    names.remove("new");
    assertTrue(names.indexOf("new") == -1);
}