Example usage for javax.swing JList setSelectionInterval

List of usage examples for javax.swing JList setSelectionInterval

Introduction

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

Prototype

public void setSelectionInterval(int anchor, int lead) 

Source Link

Document

Selects the specified interval.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);

    int start = 0;
    int end = 0;//ww  w.  ja  v  a 2  s  .  c  om
    list.setSelectionInterval(start, end);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);

    // Select the second item
    int start = 1;
    int end = 1;//from w  w  w.j ava  2 s .c o m
    list.setSelectionInterval(start, end);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);

    int start = 0;
    int end = list.getModel().getSize() - 1;
    if (end >= 0) {
        list.setSelectionInterval(start, end);
    }/*from   w ww . j  a  v  a  2  s  .co m*/
}

From source file:tourma.utils.web.WebStatistics.java

/**
 * //  w w  w  .ja  v  a  2s. c om
 */
public static String getHTML() {
    StringBuffer stats = new StringBuffer("");

    JPNStatistics jpn = new JPNStatistics();
    jpn.setSize(640, 480);
    JTabbedPane jtp = jpn.getTabbedPane();
    for (int i = 0; i < jtp.getTabCount(); i++) {
        Component comp = jtp.getComponent(i);

        if (comp instanceof ChartPanel) {
            ChartPanel panel = (ChartPanel) comp;
            panel.setSize(640, 480);
            BufferedImage buf = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
            Graphics g = buf.createGraphics();
            panel.print(g);
            g.dispose();

            //BufferedImage buf = toBufferedImage(img, 640, 480);
            String img_str = WebPicture.getPictureAsHTML(buf, 640, 480, true);
            stats.append(img_str);
        }

        if (comp instanceof JPanel) {
            // Find JList, Select All then Find ChartPanel
            JPanel pane = (JPanel) comp;
            ChartPanel panel = null;
            JList list = null;
            for (int j = 0; j < pane.getComponentCount(); j++) {
                Component c = pane.getComponent(j);
                if (c instanceof JScrollPane) {
                    for (int k = 0; k < ((JScrollPane) c).getViewport().getComponentCount(); k++) {
                        Component c2 = ((JScrollPane) c).getViewport().getComponent(k);
                        if (c2 instanceof JList) {
                            list = (JList) c2;
                        }

                    }
                }
            }

            if (list != null) {

                int start = 0;
                int end = list.getModel().getSize() - 1;
                if (end >= 0) {
                    list.setSelectionInterval(start, end);
                }

                jpn.updatePositions();
            }
            for (int j = 0; j < pane.getComponentCount(); j++) {
                Component c = pane.getComponent(j);
                if (c instanceof ChartPanel) {
                    panel = (ChartPanel) c;
                }
            }

            if (panel != null) {
                panel.setSize(640, 480);
                BufferedImage buf = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
                Graphics g = buf.createGraphics();
                panel.print(g);
                g.dispose();

                //BufferedImage buf = toBufferedImage(img, 640, 480);
                String img_str = WebPicture.getPictureAsHTML(buf, 640, 480, true);
                stats.append(img_str);
            }
        }
    }

    return stats.toString();
}

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

@Override
public void run() {
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;/*from  w  w w.j  av a 2 s. c o m*/
    }
    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 w w  . j  a v a2s  .c o  m*/
    }
    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:com.projity.pm.graphic.chart.ChartLegend.java

private void setListFields(JList list, boolean cost) {
    Object[] items = getFields(cost);
    list.setListData(items);/*from ww  w  .ja va2s  . com*/
    list.setVisibleRowCount(items.length);
    if (simple) {
        list.setSelectionInterval(0, items.length);
        list.setEnabled(false); // in simple mode, no selection allowed
    }
}

From source file:util.ui.UiUtilities.java

/**
 * Moves Selected Items from one List to another
 *
 * @param fromList/*from   w ww . ja v a  2 s.  co m*/
 *          Move from this List
 * @param toList
 *          Move into this List
 * @return Moved Elements
 */
public static Object[] moveSelectedItems(JList fromList, JList toList) {
    DefaultListModel fromModel = (DefaultListModel) fromList.getModel();
    DefaultListModel toModel = (DefaultListModel) toList.getModel();

    // get the selection
    int[] selection = fromList.getSelectedIndices();

    if (selection.length == 0) {
        return new Object[] {};
    }

    Object[] objects = new Object[selection.length];
    for (int i = 0; i < selection.length; i++) {
        objects[i] = fromModel.getElementAt(selection[i]);
    }

    // get the target insertion position
    int targetPos = toList.getMaxSelectionIndex();
    if (targetPos == -1) {
        targetPos = toModel.getSize();
    } else {
        targetPos++;
    }

    // suppress updates on both lists
    if (selection.length >= 5) {
        fromList.setModel(new DefaultListModel());
        toList.setModel(new DefaultListModel());
    }

    // move the elements
    for (int i = selection.length - 1; i >= 0; i--) {
        Object value = fromModel.remove(selection[i]);
        toModel.add(targetPos, value);
    }

    if (selection.length >= 5) {
        fromList.setModel(fromModel);
        toList.setModel(toModel);
    }

    // change selection of the fromList
    if (fromModel.getSize() > 0) {
        int newSelection = selection[0];
        if (newSelection >= fromModel.getSize()) {
            newSelection = fromModel.getSize() - 1;
        }
        fromList.setSelectedIndex(newSelection);
    }

    if (selection.length >= 5) {
        fromList.repaint();
        fromList.revalidate();
        toList.repaint();
        toList.revalidate();
    }

    // change selection of the toList
    toList.setSelectionInterval(targetPos, targetPos + selection.length - 1);

    // ensure the selection is visible
    toList.ensureIndexIsVisible(toList.getMaxSelectionIndex());
    toList.ensureIndexIsVisible(toList.getMinSelectionIndex());

    return objects;
}

From source file:util.ui.UiUtilities.java

/**
 * Moves Selected Items from one List to another
 *
 * @param fromList/*from   w w w  .  ja  v a  2  s. c  o  m*/
 *          Move from this List
 * @param toList
 *          Move into this List
 * @param row
 *          The target row where to insert
 * @return Moved Elements
 */
public static Object[] moveSelectedItems(JList fromList, JList toList, int row) {
    DefaultListModel fromModel = (DefaultListModel) fromList.getModel();
    DefaultListModel toModel = (DefaultListModel) toList.getModel();

    // get the selection
    int[] selection = fromList.getSelectedIndices();

    if (selection.length == 0) {
        return new Object[] {};
    }

    Object[] objects = new Object[selection.length];
    for (int i = 0; i < selection.length; i++) {
        objects[i] = fromModel.getElementAt(selection[i]);
    }

    // move the elements
    for (int i = selection.length - 1; i >= 0; i--) {
        Object value = fromModel.remove(selection[i]);
        toModel.insertElementAt(value, row);
    }

    // change selection of the fromList
    if (fromModel.getSize() > 0) {
        int newSelection = selection[0];
        if (newSelection >= fromModel.getSize()) {
            newSelection = fromModel.getSize() - 1;
        }
        // fromList.setSelectedIndex(-1);
    }

    // change selection of the toList
    toList.setSelectionInterval(row, row + selection.length - 1);

    // ensure the selection is visible
    toList.ensureIndexIsVisible(toList.getMaxSelectionIndex());
    toList.ensureIndexIsVisible(toList.getMinSelectionIndex());

    return objects;
}

From source file:util.ui.UiUtilities.java

/**
 * Move selected Items in the JList// w w  w  .j av  a  2 s .c o  m
 *
 * @param list
 *          Move Items in this List
 * @param row
 *          The target row where to insert
 * @param sort
 *          Dummy parameter, does nothing
 */
public static void moveSelectedItems(JList list, int row, boolean sort) {
    DefaultListModel model = (DefaultListModel) list.getModel();

    // get the selection
    int[] selection = list.getSelectedIndices();
    if (selection.length == 0) {
        return;
    }

    boolean lower = false;
    // Remove the selected items
    Object[] items = new Object[selection.length];
    for (int i = selection.length - 1; i >= 0; i--) {
        if (selection[i] < row && !lower) {
            row = row - i - 1;
            lower = true;
        }
        items[i] = model.remove(selection[i]);
    }

    for (int i = items.length - 1; i >= 0; i--) {
        model.insertElementAt(items[i], row);
    }

    // change selection of the toList
    list.setSelectionInterval(row, row + selection.length - 1);

    // ensure the selection is visible
    list.ensureIndexIsVisible(list.getMaxSelectionIndex());
    list.ensureIndexIsVisible(list.getMinSelectionIndex());
}