Example usage for javax.swing DefaultListModel insertElementAt

List of usage examples for javax.swing DefaultListModel insertElementAt

Introduction

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

Prototype

public void insertElementAt(E element, int index) 

Source Link

Document

Inserts the specified element as a component in this list at the specified index.

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 ww  w.  j a va2s  . co m*/
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < 5; j++) {
            model.addElement(labels[j]);
        }
    }
    model.insertElementAt("0", 0);

    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:ModifyModelSampleModelAction.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);/*from   w w w  .  j  av a 2 s . c  o m*/
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);

    JButton jb = new JButton("add F");

    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, "First");
            model.clear();
            model.addElement("Last");
            model.addElement("Last");
            model.addElement("Last");
            model.addElement("Last");

            int size = model.getSize();
            model.insertElementAt("Middle", size / 2);
            model.set(0, "New First");
            model.setElementAt("New Last", size - 1);

            model.remove(0);
            // model.removeAllElements();
            //    model.removeElement("Last");
            //      model.removeElementAt(size / 2);
            //        model.removeRange(0, size / 2);
        }
    });

    frame.add(jb, BorderLayout.SOUTH);

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

From source file:MainClass.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);//  w  ww . ja  va 2  s  . c o  m
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.WEST);

    ListDataListener listDataListener = new ListDataListener() {
        public void contentsChanged(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalAdded(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalRemoved(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        private void appendEvent(ListDataEvent listDataEvent) {
            switch (listDataEvent.getType()) {
            case ListDataEvent.CONTENTS_CHANGED:
                System.out.println("Type: Contents Changed");
                break;
            case ListDataEvent.INTERVAL_ADDED:
                System.out.println("Type: Interval Added");
                break;
            case ListDataEvent.INTERVAL_REMOVED:
                System.out.println("Type: Interval Removed");
                break;
            }
            System.out.println(", Index0: " + listDataEvent.getIndex0());
            System.out.println(", Index1: " + listDataEvent.getIndex1());
            DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
            System.out.println(theModel);
        }
    };

    model.addListDataListener(listDataListener);

    model.add(0, "First");
    model.addElement("Last");
    int size = model.getSize();
    model.insertElementAt("Middle", size / 2);
    size = model.getSize();
    if (size != 0)
        model.set(0, "New First");
    size = model.getSize();
    if (size != 0)
        model.setElementAt("New Last", size - 1);
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);
    }
    model.clear();
    size = model.getSize();
    if (size != 0)
        model.remove(0);

    model.removeAllElements();
    model.removeElement("Last");
    size = model.getSize();
    if (size != 0)
        model.removeElementAt(size / 2);
    size = model.getSize();
    if (size != 0)
        model.removeRange(0, size / 2);
    frame.setSize(640, 300);
    frame.setVisible(true);
}

From source file:ModifyModelSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);/*from  w  w w. j  a  v a2 s  . c  o m*/
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    contentPane.add(scrollPane1, BorderLayout.WEST);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane scrollPane2 = new JScrollPane(textArea);
    contentPane.add(scrollPane2, BorderLayout.CENTER);

    ListDataListener listDataListener = new ListDataListener() {
        public void contentsChanged(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalAdded(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalRemoved(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        private void appendEvent(ListDataEvent listDataEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            switch (listDataEvent.getType()) {
            case ListDataEvent.CONTENTS_CHANGED:
                pw.print("Type: Contents Changed");
                break;
            case ListDataEvent.INTERVAL_ADDED:
                pw.print("Type: Interval Added");
                break;
            case ListDataEvent.INTERVAL_REMOVED:
                pw.print("Type: Interval Removed");
                break;
            }
            pw.print(", Index0: " + listDataEvent.getIndex0());
            pw.print(", Index1: " + listDataEvent.getIndex1());
            DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
            Enumeration elements = theModel.elements();
            pw.print(", Elements: ");
            while (elements.hasMoreElements()) {
                pw.print(elements.nextElement());
                pw.print(",");
            }
            pw.println();
            textArea.append(sw.toString());
        }
    };

    model.addListDataListener(listDataListener);

    // Setup buttons
    JPanel jp = new JPanel(new GridLayout(2, 1));
    JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    jp.add(jp1);
    jp.add(jp2);
    JButton jb = new JButton("add F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, "First");
        }
    });
    jb = new JButton("addElement L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.addElement("Last");
        }
    });
    jb = new JButton("insertElementAt M");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            model.insertElementAt("Middle", size / 2);
        }
    });
    jb = new JButton("set F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.set(0, "New First");
        }
    });
    jb = new JButton("setElementAt L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.setElementAt("New Last", size - 1);
        }
    });
    jb = new JButton("load 10");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            for (int i = 0, n = labels.length; i < n; i++) {
                model.addElement(labels[i]);
            }
        }
    });
    jb = new JButton("clear");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.clear();
        }
    });
    jb = new JButton("remove F");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.remove(0);
        }
    });
    jb = new JButton("removeAllElements");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeAllElements();
        }
    });
    jb = new JButton("removeElement 'Last'");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeElement("Last");
        }
    });
    jb = new JButton("removeElementAt M");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeElementAt(size / 2);
        }
    });
    jb = new JButton("removeRange FM");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeRange(0, size / 2);
        }
    });
    contentPane.add(jp, BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
}

From source file:edu.ku.brc.specify.plugins.TaxonLabelFormatting.java

@Override
public void initialize(Properties propertiesArg, boolean isViewModeArg) {
    super.initialize(propertiesArg, isViewModeArg);

    String plName = "TaxonLabelFormatter";
    PickListDBAdapterIFace adapter = PickListDBAdapterFactory.getInstance().create(plName, false);
    if (adapter == null || adapter.getPickList() == null) {
        throw new RuntimeException("PickList Adapter [" + plName + "] cannot be null!");
    }//  w w w  .j a v a 2s .co m
    formatCBX = new ValComboBox(adapter);
    formatCBX.getComboBox().addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            doFormatting();
        }
    });
    formatCBX.getComboBox().addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            doFormatting();
        }
    });

    newAgentBtn = createButton(""); // Label set when new Resource Bundle is installed (below)
    searchPanel = new DBObjSearchPanel("Search", "AgentNameSearch", "AgentNameSearch",
            "edu.ku.brc.specify.datamodel.Agent", "agentId", SwingConstants.BOTTOM);
    searchPanel.getScrollPane().setMinimumSize(new Dimension(100, 200));
    searchPanel.getScrollPane().setPreferredSize(new Dimension(100, 150));
    ((FormViewObj) searchPanel.getForm()).getPanel().setBorder(null);

    try {
        UIRegistry.loadAndPushResourceBundle("specify_plugins");

        newAgentBtn.setText(getResourceString("NewAgent"));

        authorsList = new JList(new DefaultListModel());
        authorsList.setVisibleRowCount(10);
        authorsList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    Object selObj = authorsList.getSelectedValue();
                    if (selObj != null) {

                    }
                    updateEnabledState();
                }
            }
        });
        JScrollPane scrollPane = new JScrollPane(authorsList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        mapToBtn = createIconBtn("Map", "ADD_AUTHOR_NAME_TT", new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                Object agent = searchPanel.getSelectedObject();
                ((DefaultListModel) authorsList.getModel()).addElement(agent);
                doFormatting();
            }
        });
        unmapBtn = createIconBtn("Unmap", "REMOVE_AUTHOR_NAME_TT", new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                int index = authorsList.getSelectedIndex();
                if (index > -1) {
                    DefaultListModel model = (DefaultListModel) authorsList.getModel();
                    model.remove(index);
                    updateEnabledState();
                    doFormatting();
                }
            }
        });

        upBtn = createIconBtn("ReorderUp", "MOVE_AUTHOR_NAME_UP", new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                DefaultListModel model = (DefaultListModel) authorsList.getModel();
                int index = authorsList.getSelectedIndex();
                Object item = authorsList.getSelectedValue();
                model.remove(index);
                model.insertElementAt(item, index - 1);
                authorsList.setSelectedIndex(index - 1);
                updateEnabledState();
            }
        });
        downBtn = createIconBtn("ReorderDown", "MOVE_AUTHOR_NAME_DOWN", new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                DefaultListModel model = (DefaultListModel) authorsList.getModel();
                int index = authorsList.getSelectedIndex();
                Object item = authorsList.getSelectedValue();
                model.remove(index);
                model.insertElementAt(item, index + 1);
                authorsList.setSelectedIndex(index + 1);
                updateEnabledState();
            }
        });

        PanelBuilder bldr = new PanelBuilder(new FormLayout("p, 5px, p, 5px, f:p:g, 2px, p",
                "p, 4px, p, 2px, f:p:g, 4px, p, 4px, p, 2px, p, 2px, p, 2px, p"), this);
        CellConstraints cc = new CellConstraints();

        PanelBuilder upDownPanel = new PanelBuilder(new FormLayout("p", "p, 2px, p, f:p:g"));
        upDownPanel.add(upBtn, cc.xy(1, 1));
        upDownPanel.add(downBtn, cc.xy(1, 3));

        PanelBuilder middlePanel = new PanelBuilder(new FormLayout("c:p:g", "f:p:g, p, 2px, p, f:p:g"));
        middlePanel.add(mapToBtn, cc.xy(1, 2));
        middlePanel.add(unmapBtn, cc.xy(1, 4));

        PanelBuilder rwPanel = new PanelBuilder(new FormLayout("p, 2px, f:p:g", "p"));
        refWorkLabel = createLabel(getResourceString("NONE"));
        rwPanel.add(createI18NFormLabel("REFERENCEWORK"), cc.xy(1, 1));
        rwPanel.add(refWorkLabel, cc.xy(3, 1));

        int y = 1;

        bldr.add(rwPanel.getPanel(), cc.xywh(1, y, 7, 1));
        y += 2;

        bldr.add(searchPanel, cc.xywh(1, y, 1, 3));
        bldr.addSeparator(getResourceString("Authors"), cc.xy(5, y));
        y += 2;

        bldr.add(middlePanel.getPanel(), cc.xy(3, y));
        bldr.add(scrollPane, cc.xywh(5, y, 1, 3));
        bldr.add(upDownPanel.getPanel(), cc.xy(7, y));
        y += 2;

        PanelBuilder newAgentPanel = new PanelBuilder(new FormLayout("f:p:g,p", "p"));
        newAgentPanel.add(newAgentBtn, cc.xy(2, 1));

        bldr.add(newAgentPanel.getPanel(), cc.xy(1, y));
        y += 2;

        JLabel fmtLabel = createLabel(getResourceString("LABELFORMAT"));
        bldr.add(fmtLabel, cc.xy(1, y));
        y += 2;
        bldr.add(formatCBX, cc.xywh(1, y, 7, 1));
        y += 2;

        Font plain = fmtLabel.getFont();
        specialLabel = new SpecialLabel(plain, new Font(plain.getName(), Font.ITALIC, plain.getSize()));
        specialLabel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
        bldr.add(createLabel(getResourceString("SAMPLEOUTPUT") + ":"), cc.xywh(1, y, 7, 1));
        y += 2;
        bldr.add(specialLabel, cc.xywh(1, y, 7, 1));

        searchPanel.setOKBtn(mapToBtn);
    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaxonLabelFormatting.class, ex);
        log.error(ex);
        ex.printStackTrace();
    }
    UIRegistry.popResourceBundle();
}

From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java

/**
 * Revert a resource. Re-read it from the disk.
 *//*from   w  w w .j  a  v  a 2 s  .  c  o  m*/
protected void revertResource() {
    int index = levelCBX.getSelectedIndex();
    if (index > -1) {
        String exportedName = null;
        String virtualDirName = SpecifyAppContextMgr.getVirtualDirName(index);

        if (tabbedPane.getSelectedComponent() == viewsPanel) {
            SpViewSetObj vso = (SpViewSetObj) viewSetsList.getSelectedValue();
            if (vso != null) {
                exportedName = vso.getName();

                index = viewSetsList.getSelectedIndex();
                if (index > -1) {
                    viewSetsModel.remove(index);
                    contextMgr.revertViewSet(virtualDirName, vso.getName());
                    setHasChanged(true);
                }
            }
        } else {
            JList theList = tabbedPane.getSelectedComponent() == repPanel ? repList : resList;
            DefaultListModel theModel = theList == repList ? repModel : resModel;
            index = theList.getSelectedIndex();
            if (index > 0) {
                AppResourceIFace appRes = (AppResourceIFace) theList.getSelectedValue();

                AppResourceIFace revertedNewAR = contextMgr.revertResource(virtualDirName, appRes);

                setHasChanged(true);

                if (revertedNewAR != null) {
                    theModel.insertElementAt(revertedNewAR, index);
                    theList.setSelectedIndex(index);
                } else {
                    theModel.removeElementAt(index);
                    theList.clearSelection();
                }

                levelSelected();
            }
        }

        if (exportedName != null) {
            completeMsg = getLocalizedMessage("RIE_RES_REVERTED", exportedName);
        }

        enableUI();
    }
}

From source file:util.ui.UiUtilities.java

/**
 * Moves Selected Items from one List to another
 *
 * @param fromList//from  ww w  . j  a  v  a2  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/*from   w  ww. ja  va  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());
}