Example usage for javax.swing DefaultListModel indexOf

List of usage examples for javax.swing DefaultListModel indexOf

Introduction

In this page you can find the example usage for javax.swing DefaultListModel indexOf.

Prototype

public int indexOf(Object elem) 

Source Link

Document

Searches for the first occurrence of elem .

Usage

From source file:Main.java

public static void main(final String args[]) {
    String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultListModel model = new DefaultListModel();
    model.ensureCapacity(1000);/*from www.j a  v a  2  s.  co m*/
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < 5; j++) {
            model.addElement(labels[j]);
        }
    }
    System.out.println(model.indexOf("A"));

    JList jlist2 = new JList(model);
    jlist2.setVisibleRowCount(4);
    jlist2.setFixedCellHeight(12);
    jlist2.setFixedCellWidth(200);
    JScrollPane scrollPane2 = new JScrollPane(jlist2);
    frame.add(scrollPane2, BorderLayout.CENTER);

    frame.setSize(300, 350);
    frame.setVisible(true);
}

From source file:packjacket.StaticUtils.java

/**
 * Returns all the indexes of elements in a model.
 * @param model The model to search in//from w w w . j a  v a  2  s  .  c om
 * @param sa The Strings to search for
 * @return The indexes of the elements
 */
public static int[] indexesOf(DefaultListModel model, String sa[]) {
    int[] ia = new int[sa.length];
    for (int x = 0; x < sa.length; x++)
        ia[x] = model.indexOf(sa[x]);
    return ia;
}

From source file:FontChooser.java

private void jFontActionPerformed(java.awt.event.ActionEvent evt) {
    // Add your handling code here:
    DefaultListModel model = (DefaultListModel) jFontList.getModel();
    if (model.indexOf(jFont.getText()) >= 0) {
        currentFont = jFont.getText();//from   w ww.  j  ava  2 s  . co  m
        setSampleFont();
    }
}

From source file:gtu._work.ui.RegexDirReplacer.java

private void initGUI() {
    try {/*from www. j  av a  2  s.  co  m*/
        {
        }
        BorderLayout thisLayout = new BorderLayout();
        getContentPane().setLayout(thisLayout);
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("source", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    {
                        ListModel srcListModel = new DefaultListModel();
                        srcList = new JList();
                        jScrollPane1.setViewportView(srcList);
                        srcList.setModel(srcListModel);
                        {
                            panel = new JPanel();
                            jScrollPane1.setRowHeaderView(panel);
                            panel.setLayout(new FormLayout(
                                    new ColumnSpec[] { ColumnSpec.decode("default:grow"), },
                                    new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
                                            FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
                                            FormFactory.DEFAULT_ROWSPEC, }));
                            {
                                childrenDirChkbox = new JCheckBox("??");
                                childrenDirChkbox.setSelected(true);
                                panel.add(childrenDirChkbox, "1, 1");
                            }
                            {
                                subFileNameText = new JTextField();
                                panel.add(subFileNameText, "1, 2, fill, default");
                                subFileNameText.setColumns(10);
                                subFileNameText.setText("(txt|java)");
                            }
                            {
                                replaceOldFileChkbox = new JCheckBox("");
                                replaceOldFileChkbox.setSelected(true);
                                panel.add(replaceOldFileChkbox, "1, 3");
                            }
                            {
                                charsetText = new JTextField();
                                panel.add(charsetText, "1, 5, fill, default");
                                charsetText.setColumns(10);
                                charsetText.setText("UTF8");
                            }
                        }
                        srcList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                JListUtil.newInstance(srcList).defaultMouseClickOpenFile(evt);

                                JPopupMenuUtil.newInstance(srcList).applyEvent(evt)//
                                        .addJMenuItem("load files from clipboard", new ActionListener() {
                                            public void actionPerformed(ActionEvent arg0) {
                                                String content = ClipboardUtil.getInstance().getContents();
                                                DefaultListModel model = (DefaultListModel) srcList.getModel();
                                                StringTokenizer tok = new StringTokenizer(content, "\t\n\r\f",
                                                        false);
                                                for (; tok.hasMoreElements();) {
                                                    String val = ((String) tok.nextElement()).trim();
                                                    model.addElement(new File(val));
                                                }
                                            }
                                        }).show();
                            }
                        });
                        srcList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                JListUtil.newInstance(srcList).defaultJListKeyPressed(evt);
                            }
                        });
                    }
                }
                {
                    addDirFiles = new JButton();
                    jPanel1.add(addDirFiles, BorderLayout.NORTH);
                    addDirFiles.setText("add dir files");
                    addDirFiles.addActionListener(new ActionListener() {

                        public void actionPerformed(ActionEvent evt) {
                            File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog()
                                    .getApproveSelectedFile();
                            if (file == null || !file.isDirectory()) {
                                return;
                            }

                            List<File> fileLst = new ArrayList<File>();

                            String subName = StringUtils.trimToEmpty(subFileNameText.getText());
                            if (StringUtils.isBlank(subName)) {
                                subName = ".*";
                            }
                            String patternStr = ".*\\." + subName;

                            if (childrenDirChkbox.isSelected()) {
                                FileUtil.searchFileMatchs(file, patternStr, fileLst);
                            } else {
                                for (File f : file.listFiles()) {
                                    if (f.isFile() && f.getName().matches(patternStr)) {
                                        fileLst.add(f);
                                    }
                                }
                            }

                            DefaultListModel model = new DefaultListModel();
                            for (File f : fileLst) {
                                model.addElement(f);
                            }
                            srcList.setModel(model);
                        }
                    });
                }
            }
            {
                jPanel2 = new JPanel();
                BorderLayout jPanel2Layout = new BorderLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("param", null, jPanel2, null);
                {
                    exeucte = new JButton();
                    jPanel2.add(exeucte, BorderLayout.SOUTH);
                    exeucte.setText("exeucte");
                    exeucte.setPreferredSize(new java.awt.Dimension(491, 125));
                    exeucte.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            exeucteActionPerformed(evt);
                        }
                    });
                }
                {
                    jPanel3 = new JPanel();
                    GroupLayout jPanel3Layout = new GroupLayout((JComponent) jPanel3);
                    jPanel3.setLayout(jPanel3Layout);
                    jPanel2.add(jPanel3, BorderLayout.CENTER);
                    {
                        repFromText = new JTextField();
                    }
                    {
                        repToText = new JTextField();
                    }
                    jPanel3Layout.setHorizontalGroup(jPanel3Layout.createSequentialGroup()
                            .addContainerGap(25, 25)
                            .addGroup(jPanel3Layout.createParallelGroup()
                                    .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repFromText,
                                            GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repToText,
                                            GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE)))
                            .addContainerGap(20, Short.MAX_VALUE));
                    jPanel3Layout.setVerticalGroup(jPanel3Layout.createSequentialGroup().addContainerGap()
                            .addComponent(repFromText, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(repToText, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
                            .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
                }
                {
                    addToTemplate = new JButton();
                    jPanel2.add(addToTemplate, BorderLayout.NORTH);
                    addToTemplate.setText("add to template");
                    addToTemplate.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            prop.put(repFromText.getText(), repToText.getText());
                            reloadTemplateList();
                        }
                    });
                }
            }
            {
                jPanel4 = new JPanel();
                BorderLayout jPanel4Layout = new BorderLayout();
                jPanel4.setLayout(jPanel4Layout);
                jTabbedPane1.addTab("result", null, jPanel4, null);
                {
                    jScrollPane2 = new JScrollPane();
                    jPanel4.add(jScrollPane2, BorderLayout.CENTER);
                    {

                        ListModel newRepListModel = new DefaultListModel();
                        newRepList = new JList();
                        jScrollPane2.setViewportView(newRepList);
                        newRepList.setModel(newRepListModel);
                        newRepList.addMouseListener(new MouseAdapter() {
                            static final String tortoiseMergeExe = "TortoiseMerge.exe";
                            static final String commandFormat = "cmd /c call \"%s\" /base:\"%s\" /theirs:\"%s\"";

                            public void mouseClicked(MouseEvent evt) {
                                if (!JListUtil.newInstance(newRepList).isCorrectMouseClick(evt)) {
                                    return;
                                }

                                OldNewFile oldNewFile = (OldNewFile) JListUtil
                                        .getLeadSelectionObject(newRepList);

                                String base = oldNewFile.newFile.getAbsolutePath();
                                String theirs = oldNewFile.oldFile.getAbsolutePath();

                                String command = String.format(commandFormat, tortoiseMergeExe, base, theirs);

                                System.out.println(command);

                                try {
                                    Runtime.getRuntime().exec(command);
                                } catch (IOException e) {
                                    JCommonUtil.handleException(e);
                                }
                            }
                        });
                        newRepList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                Object[] objects = (Object[]) newRepList.getSelectedValues();
                                if (objects == null || objects.length == 0) {
                                    return;
                                }
                                DefaultListModel model = (DefaultListModel) newRepList.getModel();
                                int lastIndex = model.getSize() - 1;
                                Object swap = null;

                                StringBuilder dsb = new StringBuilder();
                                for (Object current : objects) {
                                    int index = model.indexOf(current);
                                    switch (evt.getKeyCode()) {
                                    case 38:// up
                                        if (index != 0) {
                                            swap = model.getElementAt(index - 1);
                                            model.setElementAt(swap, index);
                                            model.setElementAt(current, index - 1);
                                        }
                                        break;
                                    case 40:// down
                                        if (index != lastIndex) {
                                            swap = model.getElementAt(index + 1);
                                            model.setElementAt(swap, index);
                                            model.setElementAt(current, index + 1);
                                        }
                                        break;
                                    case 127:// del
                                        OldNewFile current_ = (OldNewFile) current;
                                        dsb.append(current_.newFile.getName() + "\t"
                                                + (current_.newFile.delete() ? "T" : "F") + "\n");
                                        current_.newFile.delete();
                                        model.removeElement(current);
                                    }
                                }

                                if (dsb.length() > 0) {
                                    JOptionPaneUtil.newInstance().iconInformationMessage()
                                            .showMessageDialog("del result!\n" + dsb, "DELETE");
                                }
                            }
                        });

                    }
                }
                {
                    replaceOrignFile = new JButton();
                    jPanel4.add(replaceOrignFile, BorderLayout.SOUTH);
                    replaceOrignFile.setText("replace orign file");
                    replaceOrignFile.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            DefaultListModel model = (DefaultListModel) newRepList.getModel();
                            StringBuilder sb = new StringBuilder();
                            for (int ii = 0; ii < model.size(); ii++) {
                                OldNewFile file = (OldNewFile) model.getElementAt(ii);
                                boolean delSuccess = false;
                                boolean renameSuccess = false;
                                if (delSuccess = file.oldFile.delete()) {
                                    renameSuccess = file.newFile.renameTo(file.oldFile);
                                }
                                sb.append(file.oldFile.getName() + " del:" + (delSuccess ? "T" : "F")
                                        + " rename:" + (renameSuccess ? "T" : "F") + "\n");
                            }
                            JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog(sb,
                                    getTitle());
                        }
                    });
                }
            }
            {
                jPanel5 = new JPanel();
                BorderLayout jPanel5Layout = new BorderLayout();
                jPanel5.setLayout(jPanel5Layout);
                jTabbedPane1.addTab("template", null, jPanel5, null);
                {
                    jScrollPane3 = new JScrollPane();
                    jPanel5.add(jScrollPane3, BorderLayout.CENTER);
                    {
                        templateList = new JList();
                        reloadTemplateList();
                        jScrollPane3.setViewportView(templateList);
                        templateList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                if (templateList.getLeadSelectionIndex() == -1) {
                                    return;
                                }
                                Entry<Object, Object> entry = (Entry<Object, Object>) JListUtil
                                        .getLeadSelectionObject(templateList);
                                repFromText.setText((String) entry.getKey());
                                repToText.setText((String) entry.getValue());
                            }
                        });
                        templateList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                JListUtil.newInstance(templateList).defaultJListKeyPressed(evt);
                            }
                        });
                    }
                }
                {
                    scheduleExecute = new JButton();
                    jPanel5.add(scheduleExecute, BorderLayout.SOUTH);
                    scheduleExecute.setText("schedule execute");
                    scheduleExecute.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            scheduleExecuteActionPerformed(evt);
                        }
                    });
                }
            }
        }
        this.setSize(512, 350);

        JCommonUtil.setFontAll(this.getRootPane());

        JCommonUtil.frameCloseDo(this, new WindowAdapter() {
            public void windowClosing(WindowEvent paramWindowEvent) {
                if (StringUtils.isNotBlank(repFromText.getText())) {
                    prop.put(repFromText.getText(), repToText.getText());
                }
                try {
                    prop.store(new FileOutputStream(propFile), "regexText");
                } catch (Exception e) {
                    JCommonUtil.handleException("properties store error!", e);
                }
                setVisible(false);
                dispose();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.executequery.gui.editor.ManageShortcutsPanel.java

public void addShortcut() {

    EditorSQLShortcut shortcut = new EditorSQLShortcut();
    shortcut.setShortcut(bundleString("newShortcutName"));
    shortcut.setQuery(Constants.EMPTY);/*from w  w w  . j a va  2s  .  c om*/

    DefaultListModel model = modelFromList();

    model.addElement(shortcut);
    int index = model.indexOf(shortcut);

    list.setSelectedIndex(index);
    list.scrollRectToVisible(list.getCellBounds(index, index));

    listEditingAction().actionPerformed(actionEventForEdit());
}

From source file:org.n52.ifgicopter.spf.output.GpxOutputPlugin.java

/**
 * //from   w ww  .ja  va 2s  . co m
 */
protected void updateGUI() {
    if (this.gpx == null)
        return;

    final String t = this.gpx.xmlText(GPX_OPTIONS);
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            GpxOutputPlugin.this.textPane.setText(t);

            GpxOutputPlugin.this.outputFileLabel
                    .setText("<html><b>Output file: </b>" + getGpxFilePath() + "</html>");

            DefaultListModel model = (DefaultListModel) GpxOutputPlugin.this.valuesToSaveList.getModel();
            // update list
            if (model.getSize() < GpxOutputPlugin.this.availableDataKeys.size()) {
                if (model.contains(NO_DATA_LIST_ELEMENT))
                    model.remove(model.indexOf(NO_DATA_LIST_ELEMENT));

                for (String s : GpxOutputPlugin.this.availableDataKeys) {
                    if (!model.contains(s)) {
                        model.addElement(s);
                    }
                }
            }
        }
    });
}

From source file:org.netbeans.modules.php.fuel.options.FuelPhpOptionsPanel.java

private void setAvailableNodes() {
    DefaultListModel<String> defaultListModel = new DefaultListModel<String>();
    for (String node : FuelPhp.CUSTOM_NODES) {
        defaultListModel.addElement(node);
    }//w  w  w  .  j  a va 2  s .  c  o m
    nodeList.setModel(defaultListModel);
    List<String> availableNodes = FuelPhpOptions.getInstance().getAvailableNodes();
    for (String node : availableNodes) {
        int indexOf = defaultListModel.indexOf(node);
        nodeList.addSelectionInterval(indexOf, indexOf);
    }
}

From source file:org.rimudb.editor.DescriptorEditor.java

/**
 * Build the panel/*from w  w  w  .  j a va2 s  .c  o m*/
 */
private JPanel createColumnTablePanel() {
    JPanel columnPanel = new JPanel();
    columnPanel.setLayout(new BoxLayout(columnPanel, BoxLayout.Y_AXIS));

    // Create the property table panel
    propertyModel = new PropertyTableModel();

    // Add a listener to set the changed state
    propertyModel.addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            markChanged();

            if (e instanceof PropertyTableModelEvent) {
                PropertyTableModelEvent ptme = (PropertyTableModelEvent) e;

                // If the columnName column was changed then check it isn't
                // a PK
                if (ptme.getColumn() == 1) {

                    String beforeColumnName = (String) ptme.getBeforeValue();
                    String afterColumnName = (String) ptme.getAfterValue();

                    // Is the field entry in the list of primary keys?
                    for (int i = 0; i < pkListModel.getSize(); i++) {
                        String pkColumnName = (String) pkListModel.get(i);
                        // If it's found then remove it
                        if (beforeColumnName.equals(pkColumnName)) {
                            pkListModel.set(i, afterColumnName);
                            break;
                        }
                    }

                }

            }
        }
    });

    table = new ATable(getPropertyModel());
    table.setName("ColumnTable");
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            int selectedRowCount = table.getSelectedRowCount();
            removeColumnBtn.setEnabled(selectedRowCount > 0);
            moveUpBtn.setEnabled(selectedRowCount > 0);
            moveDownBtn.setEnabled(selectedRowCount > 0);
        }
    });
    table.setTransferHandler(new TransferHandler() {

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            ATable columnTable = (ATable) c;
            int row = columnTable.getSelectedRow();
            String columnName = getPropertyModel().getRow(row).getColumnName();
            return new StringSelection(columnName);
        }
    });
    table.setDragEnabled(true);

    JScrollPane sp = new JScrollPane(table);
    sp.setMaximumSize(new Dimension(Short.MAX_VALUE, 325));
    sp.setPreferredSize(new Dimension(Short.MAX_VALUE, 325));
    sp.setMinimumSize(new Dimension(Short.MAX_VALUE, 325));

    JComboBox typeCB = new JComboBox(DatabaseTypes.getAllTypes());
    typeCB.setEditable(false);

    javax.swing.table.TableColumn typeColumn = table.getColumnModel().getColumn(2);
    typeColumn.setCellEditor(new DefaultCellEditor(typeCB));

    // Create the popup menu and set it on the table
    propertyPopup = new TablePopupMenu(this, table);
    table.addMouseListener(propertyPopup);
    sp.addMouseListener(propertyPopup);
    sp.setAlignmentX(LEFT_ALIGNMENT);

    columnPanel.add(sp);

    columnPanel.add(Box.createVerticalStrut(10));

    JLabel pkLabel = new JLabel("Primary Key Columns", SwingConstants.LEFT);
    pkLabel.setAlignmentX(LEFT_ALIGNMENT);
    columnPanel.add(pkLabel);

    pkListModel = new DefaultListModel();
    pkListModel.addListDataListener(new ListDataListener() {
        public void intervalRemoved(ListDataEvent e) {
            markChanged();
        }

        public void intervalAdded(ListDataEvent e) {
            markChanged();
        }

        public void contentsChanged(ListDataEvent e) {
            markChanged();
        }
    });

    pkList = new JList(pkListModel);
    pkList.setName("pkList");
    pkList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    pkList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            int selectedRowCount = pkList.getSelectedIndex();
            removePkBtn.setEnabled(selectedRowCount > -1);
        }
    });
    pkList.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) pkList.getModel();
            int index = dl.getIndex();

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // If this is a copy action then check we don't already have that String
            if (info.getDropAction() == COPY && listModel.indexOf(data) > -1) {
                displayDropLocation("The column " + data + " is already a primary key");
                return false;
            }

            // Perform the actual import. 
            if (dl.isInsert()) {
                int oldIndex = listModel.indexOf(data);
                if (oldIndex < index) {
                    listModel.add(index, data);
                    listModel.remove(oldIndex);
                } else {
                    listModel.remove(oldIndex);
                    listModel.add(index, data);
                }
            } else {
                // Don't handle replacements
            }
            return true;
        }

        public int getSourceActions(JComponent c) {
            return MOVE;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    pkList.setDropMode(DropMode.INSERT);
    pkList.setDragEnabled(true);

    JScrollPane pkScrollPanel = new JScrollPane(pkList);
    pkScrollPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 100));
    pkScrollPanel.setAlignmentX(LEFT_ALIGNMENT);

    columnPanel.add(pkScrollPanel);

    return columnPanel;
}