Example usage for javax.swing JList getSelectedIndex

List of usage examples for javax.swing JList getSelectedIndex

Introduction

In this page you can find the example usage for javax.swing JList getSelectedIndex.

Prototype

public int getSelectedIndex() 

Source Link

Document

Returns the smallest selected cell index; the selection when only a single item is selected in the list.

Usage

From source file:br.upe.ecomp.dosa.view.wizard.WizardAction.java

private void pickListRemoveAction(final JList sourceList, final JList destinationList) {
    if (sourceList.getSelectedValue() != null) {
        final Object element = sourceList.getSelectedValue();
        ((DefaultListModel) sourceList.getModel()).remove(sourceList.getSelectedIndex());
        ((DefaultListModel) destinationList.getModel()).addElement(element);
    }/*w w  w .ja v a  2s  .  co m*/
}

From source file:jboost.visualization.HistogramFrame.java

private JScrollPane getJScrollPane1() {
    if (jScrollPane1 == null) {
        jScrollPane1 = new JScrollPane();
        jList1 = new JList(infoParser.iterNoList);
        jList1.setLayout(new FlowLayout());
        jList1.setFocusable(false);/*from w w  w .  ja  v  a 2 s .  c  o m*/
        jList1.setIgnoreRepaint(false);
        jList1.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent evt) {
                if (!evt.getValueIsAdjusting()) {
                    JList list = (JList) evt.getSource();
                    iter = list.getSelectedIndex();
                    loadIteration(iter);
                }
            }
        });
        jScrollPane1.getViewport().add(jList1);
    }
    return jScrollPane1;
}

From source file:net.sf.jabref.exporter.ExportToClipboardAction.java

@Override
public void run() {
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;/*  ww w .  jav  a 2 s  .com*/
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        getCallBack().update();
        return;
    }

    List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values());
    Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName()));
    String[] exportFormatDisplayNames = new String[exportFormats.size()];
    for (int i = 0; i < exportFormats.size(); i++) {
        IExportFormat exportFormat = exportFormats.get(i);
        exportFormatDisplayNames[i] = exportFormat.getDisplayName();
    }

    JList<String> list = new JList<>(exportFormatDisplayNames);
    list.setBorder(BorderFactory.createEtchedBorder());
    list.setSelectionInterval(0, 0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {
                    Localization.lang("Export with selected format"), Localization.lang("Return to JabRef") },
            Localization.lang("Export with selected format"));
    if (answer == JOptionPane.NO_OPTION) {
        return;
    }

    IExportFormat format = exportFormats.get(list.getSelectedIndex());

    // Set the global variable for this database's file directory before exporting,
    // so formatters can resolve linked files correctly.
    // (This is an ugly hack!)
    Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();

    File tmp = null;
    try {
        // To simplify the exporter API we simply do a normal export to a temporary
        // file, and read the contents afterwards:
        tmp = File.createTempFile("jabrefCb", ".tmp");
        tmp.deleteOnExit();
        List<BibEntry> entries = panel.getSelectedEntries();

        // Write to file:
        format.performExport(panel.getBibDatabaseContext(), tmp.getPath(), panel.getEncoding(), entries);
        // Read the file and put the contents on the clipboard:
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new InputStreamReader(new FileInputStream(tmp), panel.getEncoding())) {
            int s;
            while ((s = reader.read()) != -1) {
                sb.append((char) s);
            }
        }
        ClipboardOwner owner = (clipboard, content) -> {
            // Do nothing
        };
        RtfSelection rs = new RtfSelection(sb.toString());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(rs, owner);
        message = Localization.lang("Entries exported to clipboard") + ": " + entries.size();

    } catch (Exception e) {
        LOGGER.error("Error exporting to clipboard", e); //To change body of catch statement use File | Settings | File Templates.
        message = Localization.lang("Error exporting to clipboard");
    } finally {
        // Clean up:
        if ((tmp != null) && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary clipboard file");
        }
    }
}

From source file:net.sf.jabref.gui.exporter.ExportToClipboardAction.java

@Override
public void run() {
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;//from w  ww  .java2 s .  com
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        getCallBack().update();
        return;
    }

    List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values());
    Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName()));
    String[] exportFormatDisplayNames = new String[exportFormats.size()];
    for (int i = 0; i < exportFormats.size(); i++) {
        IExportFormat exportFormat = exportFormats.get(i);
        exportFormatDisplayNames[i] = exportFormat.getDisplayName();
    }

    JList<String> list = new JList<>(exportFormatDisplayNames);
    list.setBorder(BorderFactory.createEtchedBorder());
    list.setSelectionInterval(0, 0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {
                    Localization.lang("Export with selected format"), Localization.lang("Return to JabRef") },
            Localization.lang("Export with selected format"));
    if (answer == JOptionPane.NO_OPTION) {
        return;
    }

    IExportFormat format = exportFormats.get(list.getSelectedIndex());

    // Set the global variable for this database's file directory before exporting,
    // so formatters can resolve linked files correctly.
    // (This is an ugly hack!)
    Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();

    File tmp = null;
    try {
        // To simplify the exporter API we simply do a normal export to a temporary
        // file, and read the contents afterwards:
        tmp = File.createTempFile("jabrefCb", ".tmp");
        tmp.deleteOnExit();
        List<BibEntry> entries = panel.getSelectedEntries();

        // Write to file:
        format.performExport(panel.getBibDatabaseContext(), tmp.getPath(),
                panel.getBibDatabaseContext().getMetaData().getEncoding(), entries);
        // Read the file and put the contents on the clipboard:
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new InputStreamReader(new FileInputStream(tmp),
                panel.getBibDatabaseContext().getMetaData().getEncoding())) {
            int s;
            while ((s = reader.read()) != -1) {
                sb.append((char) s);
            }
        }
        ClipboardOwner owner = (clipboard, content) -> {
            // Do nothing
        };
        RtfSelection rs = new RtfSelection(sb.toString());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(rs, owner);
        message = Localization.lang("Entries exported to clipboard") + ": " + entries.size();

    } catch (Exception e) {
        LOGGER.error("Error exporting to clipboard", e); //To change body of catch statement use File | Settings | File Templates.
        message = Localization.lang("Error exporting to clipboard");
    } finally {
        // Clean up:
        if ((tmp != null) && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary clipboard file");
        }
    }
}

From source file:fr.free.hd.servers.gui.FaceView.java

@Override
protected JComponent createControl() {
    final GridBagLayout layout = new GridBagLayout();
    final JPanel view = new JPanel(layout);

    //Face list/* w w  w . j  a v a  2  s . co m*/
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 0;
    c.gridheight = 3;
    c.weighty = 0.75;
    c.weightx = 0.15;
    c.fill = GridBagConstraints.BOTH;
    final JList facesList = CreateList();
    facesList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (facesList.getSelectedIndex() != -1) {
                    face = (Face) facesList.getSelectedValue();
                    updateLabel();
                } else {

                }
            }
        }
    });
    view.add(facesList, c);

    // New button
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 3;
    c.fill = GridBagConstraints.BOTH;
    JButton btnNew = new JButton("Nouveau");
    btnNew.setEnabled(false);
    view.add(btnNew, c);

    // Save button
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 4;
    c.fill = GridBagConstraints.BOTH;
    JButton btnModified = new JButton("Modifier");
    btnModified.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            facesDAO.storeFace(face);
        }
    });
    view.add(btnModified, c);

    //Draw Face
    c = new GridBagConstraints();
    c.gridx = 1;
    c.gridy = 0;
    c.gridheight = 5;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 0.60;
    lblFace = new JLabel();
    view.add(lblFace, c);

    //Hand Panel
    c = new GridBagConstraints();
    c.gridx = 2;
    c.gridy = 0;
    c.weightx = 0.15;
    c.fill = GridBagConstraints.BOTH;
    JPanel pnlHand = createPosition();
    view.add(pnlHand, c);

    //Mouth Panel
    c = new GridBagConstraints();
    c.gridx = 2;
    c.gridy = 1;
    c.weightx = 0.15;
    c.fill = GridBagConstraints.BOTH;
    JPanel pnlKind = createKind();
    view.add(pnlKind, c);

    //Mouth Panel
    c = new GridBagConstraints();
    c.gridx = 2;
    c.gridy = 2;
    c.weightx = 0.15;
    c.fill = GridBagConstraints.BOTH;
    JPanel pnlMouth = createMouth();
    view.add(pnlMouth, c);

    // Picture filename
    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 5;
    c.gridwidth = 2;
    c.fill = GridBagConstraints.BOTH;
    JTextField txtPath = new JTextField();
    view.add(txtPath, c);

    //Browse Button
    c = new GridBagConstraints();
    c.gridx = 2;
    c.gridy = 5;
    c.fill = GridBagConstraints.BOTH;
    JButton btnBrownse = new JButton("Browse");
    view.add(btnBrownse, c);

    //Select default face
    if (facesList.getModel().getSize() > 0) {
        facesList.setSelectedIndex(0);
        position = HandPositionEnum.HAND_POSITION_MENTON;
        kind = HandKeyEnum.HAND_KEY_2V;
    }

    return view;
}

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

/**
 * Moves selected items from one list to the other.
 * @param srcList//from   w  w w.j a v a 2  s . com
 * @param srcHash
 * @param dstList
 * @param dstHash
 */
private void moveItems(final JList srcList, final HashSet<Integer> srcHash, final JList dstList,
        final HashSet<Integer> dstHash) {
    int inx = srcList.getSelectedIndex();
    if (inx > -1) {
        DefaultListModel srcModel = (DefaultListModel) srcList.getModel();
        DefaultListModel dstModel = (DefaultListModel) dstList.getModel();

        int[] indexes = srcList.getSelectedIndices();
        ArrayList<LatLonPoint> llpList = new ArrayList<LatLonPoint>(indexes.length);
        for (int selInx : indexes) {
            LatLonPoint llp = (LatLonPoint) srcModel.get(selInx);
            llpList.add(llp);

            if (!dstHash.contains(llp.getLocId())) {
                dstModel.addElement(llp);
                dstHash.add(llp.getLocId());
            }
        }

        for (LatLonPoint llp : llpList) {
            srcModel.removeElement(llp);
            srcHash.remove(llp.getLocId());
        }
    }
}

From source file:DragListDemo.java

public boolean importData(JComponent c, Transferable t) {
    JList target = null;
    ArrayList alist = null;/*from   w w w . ja v a2 s . c  o m*/
    if (!canImport(c, t.getTransferDataFlavors())) {
        return false;
    }
    try {
        target = (JList) c;
        if (hasLocalArrayListFlavor(t.getTransferDataFlavors())) {
            alist = (ArrayList) t.getTransferData(localArrayListFlavor);
        } else if (hasSerialArrayListFlavor(t.getTransferDataFlavors())) {
            alist = (ArrayList) t.getTransferData(serialArrayListFlavor);
        } else {
            return false;
        }
    } catch (UnsupportedFlavorException ufe) {
        System.out.println("importData: unsupported data flavor");
        return false;
    } catch (IOException ioe) {
        System.out.println("importData: I/O exception");
        return false;
    }

    //At this point we use the same code to retrieve the data
    //locally or serially.

    //We'll drop at the current selected index.
    int index = target.getSelectedIndex();

    //Prevent the user from dropping data back on itself.
    //For example, if the user is moving items #4,#5,#6 and #7 and
    //attempts to insert the items after item #5, this would
    //be problematic when removing the original items.
    //This is interpreted as dropping the same data on itself
    //and has no effect.
    if (source.equals(target)) {
        if (indices != null && index >= indices[0] - 1 && index <= indices[indices.length - 1]) {
            indices = null;
            return true;
        }
    }

    DefaultListModel listModel = (DefaultListModel) target.getModel();
    int max = listModel.getSize();
    if (index < 0) {
        index = max;
    } else {
        index++;
        if (index > max) {
            index = max;
        }
    }
    addIndex = index;
    addCount = alist.size();
    for (int i = 0; i < alist.size(); i++) {
        listModel.add(index++, alist.get(i));
    }
    return true;
}

From source file:ListCutPaste.java

/**
 * Perform the actual data import./* www .  j  a  v a 2  s .c  om*/
 */
public boolean importData(TransferHandler.TransferSupport info) {
    String data = null;

    // If we can't handle the import, bail now.
    if (!canImport(info)) {
        return false;
    }

    JList list = (JList) info.getComponent();
    DefaultListModel model = (DefaultListModel) list.getModel();
    // Fetch the data -- bail if this fails
    try {
        data = (String) info.getTransferable().getTransferData(DataFlavor.stringFlavor);
    } catch (UnsupportedFlavorException ufe) {
        System.out.println("importData: unsupported data flavor");
        return false;
    } catch (IOException ioe) {
        System.out.println("importData: I/O exception");
        return false;
    }

    if (info.isDrop()) { // This is a drop
        JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
        int index = dl.getIndex();
        if (dl.isInsert()) {
            model.add(index, data);
            return true;
        } else {
            model.set(index, data);
            return true;
        }
    } else { // This is a paste
        int index = list.getSelectedIndex();
        // if there is a valid selection,
        // insert data after the selection
        if (index >= 0) {
            model.add(list.getSelectedIndex() + 1, data);
            // else append to the end of the list
        } else {
            model.addElement(data);
        }
        return true;
    }
}

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

public void valueChanged(final ListSelectionEvent e) {
    //log.debug("valueChanged: "+(e != null ? ((JMenuItem)e.getSource()).getText() : "null"));
    //log.debug("valueChanged: "+(e != null ? e.getClass().getSimpleName() : "null")+" "+e.getSource().getClass().getSimpleName());
    if (e != null) {
        if (e.getSource() instanceof TextFieldWithQuery.AddItemEvent) {
            doNewAction(((TextFieldWithQuery.AddItemEvent) e.getSource()).value);
            return;
        } else if (e.getSource() instanceof TextFieldWithQuery) {
            if (((TextFieldWithQuery) e.getSource()).getTextField().getText().length() == 0) {
                dataObj = null;/*  w  w w .j  av a 2s.  c om*/
            }
        } else {
            String itemLabel = null;
            if (e.getSource() instanceof JMenuItem) {
                itemLabel = ((JMenuItem) e.getSource()).getText().toString();
                this.dataObj = null;
                getValue();
                refreshUIFromData(true);

            } else if (e.getSource() instanceof JList) {
                JList listBox = (JList) e.getSource();
                if (listBox.getSelectedIndex() > -1) {
                    itemLabel = listBox.getSelectedValue().toString();
                    this.dataObj = null;
                    getValue();
                } else {
                    return;
                }
            }
        }
    }

    isChanged = true;
    valueHasChanged();
    validateState();

    boolean doEnable = dataObj != null || (textWithQuery != null && textWithQuery.getSelectedId() != null);
    if (editBtn != null) {
        editBtn.setEnabled(doEnable);
    }
    if (cloneBtn != null) {
        cloneBtn.setEnabled(doEnable);
    }
    notifyListeners(e);

    repaint();
}

From source file:de.dakror.virtualhub.client.dialog.ChooseCatalogDialog.java

public static void show(ClientFrame frame, final JSONArray data) {
    final JDialog dialog = new JDialog(frame, "Katalog whlen", true);
    dialog.setSize(400, 300);/*from w ww  .j a  va  2  s .  c  o  m*/
    dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    dialog.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            Client.currentClient.disconnect();
            System.exit(0);
        }
    });

    JPanel contentPane = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
    dialog.setContentPane(contentPane);
    DefaultListModel dlm = new DefaultListModel();
    for (int i = 0; i < data.length(); i++) {
        try {
            dlm.addElement(data.getJSONObject(i).getString("name"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    final JList catalogs = new JList(dlm);
    catalogs.setDragEnabled(false);
    catalogs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JScrollPane jsp = new JScrollPane(catalogs, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    jsp.setPreferredSize(new Dimension(396, 200));
    contentPane.add(jsp);

    JPanel mods = new JPanel(new GridLayout(1, 2));
    mods.setPreferredSize(new Dimension(50, 22));
    mods.add(new JButton(new AbstractAction("+") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            String name = JOptionPane.showInputDialog(dialog,
                    "Bitte geben Sie den Namen des neuen Katalogs ein.", "Katalog hinzufgen",
                    JOptionPane.PLAIN_MESSAGE);
            if (name != null && name.length() > 0) {
                DefaultListModel dlm = (DefaultListModel) catalogs.getModel();
                for (int i = 0; i < dlm.getSize(); i++) {
                    if (dlm.get(i).toString().equals(name)) {
                        JOptionPane.showMessageDialog(dialog,
                                "Es existert bereits ein Katalog mit diesem Namen!",
                                "Katalog bereits vorhanden!", JOptionPane.ERROR_MESSAGE);
                        actionPerformed(e);
                        return;
                    }
                }

                try {
                    dlm.addElement(name);
                    JSONObject o = new JSONObject();
                    o.put("name", name);
                    o.put("sources", new JSONArray());
                    o.put("tags", new JSONArray());
                    data.put(o);
                    Client.currentClient.sendPacket(new Packet0Catalogs(data));
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }));
    mods.add(new JButton(new AbstractAction("-") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (catalogs.getSelectedIndex() != -1) {
                if (JOptionPane.showConfirmDialog(dialog,
                        "Sind Sie sicher, dass Sie diesen\r\nKatalog unwiderruflich lschen wollen?",
                        "Katalog lschen", JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                    DefaultListModel dlm = (DefaultListModel) catalogs.getModel();
                    data.remove(catalogs.getSelectedIndex());
                    dlm.remove(catalogs.getSelectedIndex());
                    try {
                        Client.currentClient.sendPacket(new Packet0Catalogs(data));
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }));

    contentPane.add(mods);

    JLabel l = new JLabel("");
    l.setPreferredSize(new Dimension(396, 14));
    contentPane.add(l);

    JSeparator sep = new JSeparator(JSeparator.HORIZONTAL);
    sep.setPreferredSize(new Dimension(396, 10));
    contentPane.add(sep);

    JPanel buttons = new JPanel(new GridLayout(1, 2));
    buttons.setPreferredSize(new Dimension(396, 22));
    buttons.add(new JButton(new AbstractAction("Abbrechen") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            Client.currentClient.disconnect();
            System.exit(0);
        }
    }));
    buttons.add(new JButton(new AbstractAction("Katalog whlen") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (catalogs.getSelectedIndex() != -1) {
                try {
                    Client.currentClient
                            .setCatalog(new Catalog(data.getJSONObject(catalogs.getSelectedIndex())));
                    Client.currentClient.frame.setTitle("- " + Client.currentClient.getCatalog().getName());
                    dialog.dispose();
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }));

    dialog.add(buttons);

    dialog.setLocationRelativeTo(frame);
    dialog.setResizable(false);
    dialog.setVisible(true);
}