Example usage for javax.swing ListModel getElementAt

List of usage examples for javax.swing ListModel getElementAt

Introduction

In this page you can find the example usage for javax.swing ListModel getElementAt.

Prototype

E getElementAt(int index);

Source Link

Document

Returns the value at the specified index.

Usage

From source file:com.kstenschke.copypastestack.ToolWindow.java

/**
 * Bubble all color-tagged items to the top of the list (groups: yellow, green, reed, untagged)
 *///w  w w .  java 2 s . com
private void sortClipboardListByTags(boolean sortAlphabetically) {
    ListModel<String> listModel = this.form.listClipItems.getModel();
    int amountItems = listModel.getSize();

    if (amountItems > 0) {
        String[] itemsYellow = new String[amountItems + 1];
        int indexYellow = 0;

        String[] itemsGreen = new String[amountItems + 1];
        int indexGreen = 0;

        String[] itemsRed = new String[amountItems + 1];
        int indexRed = 0;

        String[] itemsUntagged = new String[amountItems + 1];
        int indexUntagged = 0;

        // Refill items from listModel into sortable arrays
        for (int i = 0; i < amountItems; i++) {
            String item = listModel.getElementAt(i);
            if (item != null && !item.trim().isEmpty()) {
                switch (TagManager.getIdColorByValue(item)) {
                case StaticValues.ID_COLOR_YELLOW:
                    itemsYellow[indexYellow] = item;
                    indexYellow++;
                    break;

                case StaticValues.ID_COLOR_GREEN:
                    itemsGreen[indexGreen] = item;
                    indexGreen++;
                    break;

                case StaticValues.ID_COLOR_RED:
                    itemsRed[indexRed] = item;
                    indexRed++;
                    break;

                case StaticValues.ID_COLOR_NONE:
                    itemsUntagged[indexUntagged] = item;
                    indexUntagged++;
                    break;
                }
            }
        }

        // Reduce arrays to size of actual content
        itemsYellow = Arrays.copyOfRange(itemsYellow, 0, indexYellow);
        itemsRed = Arrays.copyOfRange(itemsRed, 0, indexRed);
        itemsGreen = Arrays.copyOfRange(itemsGreen, 0, indexGreen);
        itemsUntagged = Arrays.copyOfRange(itemsUntagged, 0, indexUntagged);

        // Sort string items alphabetically
        if (sortAlphabetically) {
            if (itemsYellow.length > 1)
                Arrays.sort(itemsYellow, String.CASE_INSENSITIVE_ORDER);
            if (itemsGreen.length > 1)
                Arrays.sort(itemsGreen, String.CASE_INSENSITIVE_ORDER);
            if (itemsRed.length > 1)
                Arrays.sort(itemsRed, String.CASE_INSENSITIVE_ORDER);
            if (itemsUntagged.length > 1)
                Arrays.sort(itemsUntagged, String.CASE_INSENSITIVE_ORDER);
        }

        // Update list from sorted items
        this.setClipboardListData(ArrayUtils.addAll(
                ArrayUtils.addAll(ArrayUtils.addAll(itemsYellow, itemsGreen), itemsRed), itemsUntagged), false);
    }
}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Sets the selected items on a {@link JList}, which is a tedious task to do by hand.
 * @param selection The items that should be selected in the list
 * @param list The list itself//from   w w  w  . java  2s. c o m
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void setJListSelection(List selection, JList list) {

    // Load JList model data in array list
    List modelItems = new ArrayList();
    ListModel listModel = list.getModel();
    for (int i = 0; i < listModel.getSize(); i++) {
        modelItems.add(listModel.getElementAt(i));
    }

    // Determine indices of selection items
    List indices = new ArrayList();
    Iterator items = selection.iterator();
    while (items.hasNext()) {
        Object item = items.next();
        int index = modelItems.indexOf(item);
        if (index != -1) {
            indices.add(new Integer(index));
        }
    }

    // Convert Integer list to int array (man, this is awkward...)
    int[] indicesArr = new int[indices.size()];
    for (int i = 0; i < indices.size(); i++) {
        indicesArr[i] = ((Integer) indices.get(i)).intValue();
    }

    // Set selection
    list.setSelectedIndices(indicesArr);

}

From source file:com.googlecode.vfsjfilechooser2.filepane.VFSFilePane.java

public JPanel createList() {
    JPanel p = new JPanel(new BorderLayout());
    final VFSJFileChooser fileChooser = getFileChooser();
    final JList aList = new JList() {
        @Override//from   w w  w  . j ava 2  s  .c  o  m
        public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
            ListModel model = getModel();
            int max = model.getSize();

            if ((prefix == null) || (startIndex < 0) || (startIndex >= max)) {
                throw new IllegalArgumentException();
            }

            // start search from the next element before/after the selected element
            boolean backwards = (bias == Position.Bias.Backward);

            for (int i = startIndex; backwards ? (i >= 0) : (i < max); i += (backwards ? (-1) : 1)) {
                String filename = fileChooser.getName((FileObject) model.getElementAt(i));

                if (filename.regionMatches(true, 0, prefix, 0, prefix.length())) {
                    return i;
                }
            }

            return -1;
        }
    };

    aList.setCellRenderer(new FileRenderer());
    aList.setLayoutOrientation(JList.VERTICAL_WRAP);

    // 4835633 : tell BasicListUI that this is a file list
    aList.putClientProperty("List.isFileList", Boolean.TRUE);

    if (listViewWindowsStyle) {
        aList.addFocusListener(repaintListener);
    }

    updateListRowCount(aList);

    getModel().addListDataListener(new ListDataListener() {
        public void intervalAdded(ListDataEvent e) {
            updateListRowCount(aList);
        }

        public void intervalRemoved(ListDataEvent e) {
            updateListRowCount(aList);
        }

        public void contentsChanged(ListDataEvent e) {
            if (isShowing()) {
                clearSelection();
            }

            updateListRowCount(aList);
        }
    });

    getModel().addPropertyChangeListener(this);

    if (fileChooser.isMultiSelectionEnabled()) {
        aList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    } else {
        aList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    aList.setModel(getModel());

    aList.addListSelectionListener(createListSelectionListener());
    aList.addMouseListener(getMouseHandler());

    JScrollPane scrollpane = new JScrollPane(aList);

    if (listViewBackground != null) {
        aList.setBackground(listViewBackground);
    }

    if (listViewBorder != null) {
        scrollpane.setBorder(listViewBorder);
    }

    p.add(scrollpane, BorderLayout.CENTER);

    return p;
}

From source file:Sales.TabbedPaneWin.java

private void renewAgreementBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renewAgreementBtnActionPerformed
    ListModel lModel = jList1.getModel();
    String[] arr = new String[lModel.getSize()];

    String AgreementID = agreementIdTxtF1.getText();
    String ClientID = clientIdTxtF4.getText();

    //Getting/*www . ja  v a 2 s .c  o  m*/
    OOAgreement.setAGREEMENTID(AgreementID);
    OOAgreement.setCLIENTID(ClientID);
    OOAgreement.setFROM(((JTextField) fromDateChooser.getDateEditor().getUiComponent()).getText());//downcasting UI-> hierachy
    OOAgreement.setTO(((JTextField) toDateChooser.getDateEditor().getUiComponent()).getText());
    OOAgreement.setTYPE(agTypeComboBox.getSelectedItem().toString());
    for (int i = 0; i < lModel.getSize(); i++) {
        arr[i] = (String) lModel.getElementAt(i);
    }

    OOAgreement.setASESTS(arr);

    if (Validate.isValidClientId(clientIdTxtF4.getText())) {
        if (Validate.isValidAgreementId(agreementIdTxtF1.getText())) {
            try {
                if (Validate.isValidCurrentDate(
                        ((JTextField) fromDateChooser.getDateEditor().getUiComponent()).getText())) {
                    if (Validate.isValidCurrentDate(
                            ((JTextField) toDateChooser.getDateEditor().getUiComponent()).getText())) {
                        try {
                            if (OOAgreement.update(lModel.getSize())) {//row count (0,1,2..) or (0) for nothing
                                jTable1.setModel(DbUtils.resultSetToTableModel(dispalyTableExpiary()));
                                JOptionPane.showMessageDialog(null, "Agreement " + AgreementID + " With Client "
                                        + ClientID + " Renewal Successfull");

                                resetAgreementFields();

                            } else {
                                JOptionPane.showMessageDialog(null, "Error: AgreementID not found..");
                            }
                        } catch (Exception ex) {
                            Logger.getLogger(TabbedPaneWin.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        jLabel67.setVisible(true);

                        JOptionPane.showMessageDialog(null, "Enter valid Renew Date ...");

                    }
                } else {
                    jLabel75.setVisible(true);

                    JOptionPane.showMessageDialog(null, "Enter valid current Date or Reset ...");

                }
            } catch (ParseException ex) {
                Logger.getLogger(TabbedPaneWin.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            jLabel71.setVisible(true);

            JOptionPane.showMessageDialog(null, "Enter AgreeementId in given form...");

        }
    } else {
        jLabel74.setVisible(true);

        JOptionPane.showMessageDialog(null, "Enter ClientID in given form...");

    }

    jLabel74.setVisible(false);
    jLabel75.setVisible(false);
    jLabel67.setVisible(false);
    jLabel76.setVisible(false);

}

From source file:edu.ku.brc.af.ui.forms.FormViewObj.java

/**
 * Sets the appropriate index in the list box
 * @param list the list box//from  w  w  w  .  j a va  2 s  .  c o m
 * @param data the data value
 */
protected static void setListValue(final JList list, final Object data) {

    Iterator<?> iter = null;
    if (data instanceof Set<?>) {
        iter = ((Set<?>) data).iterator();

    } else if (data instanceof org.hibernate.collection.PersistentSet) {
        iter = ((org.hibernate.collection.PersistentSet) data).iterator();
    }

    if (iter != null) {
        DefaultListModel defModel = new DefaultListModel();
        while (iter.hasNext()) {
            defModel.addElement(iter.next());
        }
        list.setModel(defModel);

    } else {
        ListModel model = list.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            Object item = model.getElementAt(i);
            if (item instanceof String) {
                if (((String) item).equals(data)) {
                    list.setSelectedIndex(i);
                    return;
                }
            } else if (item.equals(data)) {
                list.setSelectedIndex(i);
                return;
            }
        }
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java

/**
 * Updates lists in list panel to display field as the current selection.
 * /* ww w. j a va2 s  .c o m*/
 * @param field
 */
protected void displayField(final FieldQRI field) {
    List<TableTreePathPoint> displayedPath = getCurrentDisplayPath();
    List<TableTreePathPoint> fieldPath = field.getTableTree().getPathFromRoot();

    if (tableTreeList.size() != listBoxPanel.getComponentCount() - 1) {
        log.error("tableTreeList and listBoxPanel are out of sync");
    }

    int p = 0;
    while (p < displayedPath.size() && p < fieldPath.size()) {
        if (!displayedPath.get(p).equals(fieldPath.get(p))) {
            break;
        }
        p++;
    }
    if (!(p == fieldPath.size() && fieldPath.size() == displayedPath.size())) {
        if (p == fieldPath.size()) {
            if (p == 1) {
                fillNextList(tableList);
            } else {
                fillNextList(listBoxList.get(p - 2));
            }
        } else {
            p--;
            while (p < fieldPath.size() - 1) {
                JList currList = p < 0 ? tableList : listBoxList.get(p);
                ListModel model = currList.getModel();
                // find and select item in path
                int i = 0;
                boolean foundPathItem = false;
                while (i < model.getSize() && !foundPathItem) {
                    QryListRendererIFace item = (BaseQRI) model.getElementAt(i);
                    if (item.hasChildren()) {
                        TableTree tt = ((BaseQRI) item).getTableTree();
                        if (fieldPath.get(p + 1).equals(new TableTreePathPoint(tt))) {
                            currList.setSelectedIndex(i);
                            foundPathItem = true;
                        }
                    }
                    i++;
                }
                if (foundPathItem) {
                    //fillNextList(currList);
                    p++;
                } else {
                    log.error("unable to locate field: " + field.getFieldName());
                    return;
                }
            }
        }
    }
    ListModel model = listBoxList.get(fieldPath.size() - 1).getModel();
    for (int f = 0; f < model.getSize(); f++) {
        BaseQRI item = (BaseQRI) model.getElementAt(f);
        if (item.getTitle().equals(field.getTitle())) {
            processingLists = true;
            listBoxList.get(fieldPath.size() - 1).setSelectedIndex(f);
            listBoxList.get(fieldPath.size() - 1).ensureIndexIsVisible(f);
            processingLists = false;
            break;
        }
    }

}

From source file:Sales.TabbedPaneWin.java

private void addAgreementBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAgreementBtnActionPerformed
    ListModel lModel = jList1.getModel();
    String[] arr = new String[lModel.getSize()];

    if (Validate.isValidClientId(clientIdTxtF4.getText())) {
        if (Validate.isValidAgreementId(agreementIdTxtF1.getText())) {
            if (true) {
                if (true) {

                    try {
                        OOAgreement.setAGREEMENTID(agreementIdTxtF1.getText());
                        OOAgreement.setCLIENTID(clientIdTxtF4.getText());
                        OOAgreement.setFROM(
                                ((JTextField) fromDateChooser.getDateEditor().getUiComponent()).getText());//downcasting UI-> hierachy
                        OOAgreement//from   www  .  ja  va2  s.co m
                                .setTO(((JTextField) toDateChooser.getDateEditor().getUiComponent()).getText());
                        OOAgreement.setTYPE(agTypeComboBox.getSelectedItem().toString());

                        for (int i = 0; i < lModel.getSize(); i++) {
                            arr[i] = (String) lModel.getElementAt(i);
                        }

                        OOAgreement.setASESTS(arr);
                        //insert
                        if (OOAgreement.insert(lModel.getSize())) {//row count (0,1,2..) or (0) for nothing,,,,,,Getting model size and passing to insert model for futher op

                            JOptionPane.showMessageDialog(null, "Adding Agreement Successfull");
                            jTable1.setModel(DbUtils.resultSetToTableModel(dispalyTableExpiary()));

                            resetAgreementFields();
                        } else {
                            JOptionPane.showMessageDialog(null, "Error: Use existing ClientID..");
                        }
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(TabbedPaneWin.class.getName()).log(Level.SEVERE, null, ex);//Logiing errors
                        System.err.println(ex.getMessage());
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Unkown Error",
                                JOptionPane.ERROR_MESSAGE);//if needed show in clients interface
                    } catch (Exception ex) {
                        Logger.getLogger(TabbedPaneWin.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } else {
                    jLabel67.setVisible(true);

                    JOptionPane.showMessageDialog(null, "Enter valid Renew Date ...");

                }
            } else {
                jLabel75.setVisible(true);

                JOptionPane.showMessageDialog(null, "Enter valid current Date or Reset ...");

            }
        } else {
            jLabel71.setVisible(true);

            JOptionPane.showMessageDialog(null, "Enter AgreeementId in given form...");

        }
    } else {
        jLabel76.setVisible(true);

        JOptionPane.showMessageDialog(null, "Enter ClientID in given form...");

    }

    jLabel71.setVisible(false);
    jLabel74.setVisible(false);
    jLabel75.setVisible(false);
    jLabel67.setVisible(false);
    jLabel76.setVisible(false);

}

From source file:op.tools.DlgListSelector.java

private void btnApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnApplyActionPerformed
    ListModel lm = lstSelect.getModel();
    ListSelectionModel lsm = lstSelect.getSelectionModel();
    result = lm.getElementAt(lsm.getLeadSelectionIndex());
    dispose();//w  w w.j a  v  a 2  s .c om

}

From source file:org.clipsmonitor.gui.MapGeneratorTopComponent.java

private void PersonPathListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_PersonPathListValueChanged
    ListModel<String> listmodel = PersonPathList.getModel();
    if (PersonPathList.getSelectedIndex() >= 0) {
        String pathname = listmodel.getElementAt(PersonPathList.getSelectedIndex());
        String[] split = pathname.split("_");
        state = split[0];/*from  w w  w. ja  v  a2 s  . c  om*/
        setState(state);
        updateLabel(state);
        actualPath = model.getLastPathOfPerson(state);
        MakeMoveList(-1, -1, pathname);
        String[][] move = model.getMoveCellMap(pathname, -1);
        model.ApplyUpdateOnMoveMap(move);
        model.CopyToActive(model.getMove());
        PreviewMap.repaint();
        setListEnable();
    }
}

From source file:org.eclipse.wb.internal.swing.model.property.editor.models.list.ListModelPropertyEditor.java

/**
 * @return the items specified in value of given {@link Property}.
 *//*from  w ww  . j a va 2 s. c om*/
public static String[] getItems(Property property) throws Exception {
    Object value = property.getValue();
    if (value instanceof ListModel) {
        List<String> items = Lists.newArrayList();
        ListModel model = (ListModel) value;
        for (int i = 0; i < model.getSize(); i++) {
            Object element = model.getElementAt(i);
            if (element instanceof String) {
                items.add((String) element);
            }
        }
        return items.toArray(new String[items.size()]);
    }
    // no items
    return ArrayUtils.EMPTY_STRING_ARRAY;
}