Example usage for javax.swing DefaultListModel addElement

List of usage examples for javax.swing DefaultListModel addElement

Introduction

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

Prototype

public void addElement(E element) 

Source Link

Document

Adds the specified component to the end of this list.

Usage

From source file:au.org.ala.delta.intkey.ui.OpenDataSetDialog.java

public OpenDataSetDialog(Frame owner, List<Pair<String, String>> datasetIndexData, File startBrowseDirectory) {
    super(owner, true);
    setPreferredSize(new Dimension(450, 300));

    ActionMap actionMap = Application.getInstance().getContext().getActionMap(this);
    ResourceMap resourceMap = Application.getInstance().getContext().getResourceMap(OpenDataSetDialog.class);
    resourceMap.injectFields(this);

    setTitle(title);// ww w .  j av  a  2s .c o m

    _selectedDatasetPath = null;

    _pnlList = new JPanel();
    _pnlList.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(_pnlList, BorderLayout.CENTER);
    _pnlList.setLayout(new BorderLayout(0, 0));

    _lblSelectByTitle = new JLabel(selectByTitleCaption);
    _pnlList.add(_lblSelectByTitle, BorderLayout.NORTH);

    _sclPnList = new JScrollPane();
    _pnlList.add(_sclPnList, BorderLayout.CENTER);

    _listDatasetIndex = new JList();
    _sclPnList.setViewportView(_listDatasetIndex);

    _pnlBottom = new JPanel();
    _pnlBottom.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(_pnlBottom, BorderLayout.SOUTH);
    _pnlBottom.setLayout(new BorderLayout(0, 0));

    _lblSelectByFileName = new JLabel(selectByFileCaption);
    _pnlBottom.add(_lblSelectByFileName, BorderLayout.NORTH);

    _pnlButtons = new JPanel();
    _pnlButtons.setBorder(new EmptyBorder(10, 0, 0, 0));
    _pnlBottom.add(_pnlButtons, BorderLayout.SOUTH);

    _btnOK = new JButton();
    _btnOK.setAction(actionMap.get("OpenDataSetDialog_OK"));
    _pnlButtons.add(_btnOK);

    _btnCancel = new JButton();
    _btnCancel.setAction(actionMap.get("OpenDataSetDialog_Cancel"));
    _pnlButtons.add(_btnCancel);

    _btnHelp = new JButton();
    _btnHelp.setAction(actionMap.get("OpenDataSetDialog_Help"));
    _pnlButtons.add(_btnHelp);

    _pnlFile = new JPanel();
    _pnlBottom.add(_pnlFile, BorderLayout.CENTER);
    _pnlFile.setLayout(new BorderLayout(0, 0));

    _txtFldFileName = new JTextField();
    _pnlFile.add(_txtFldFileName, BorderLayout.CENTER);
    _txtFldFileName.setColumns(10);
    _txtFldFileName.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            // Clear any selected item in the list of the text field is
            // modified.
            _listDatasetIndex.clearSelection();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            // do nothing
        }

        @Override
        public void keyPressed(KeyEvent e) {
            // do nothing

        }
    });

    _btnBrowse = new JButton();
    _btnBrowse.setAction(actionMap.get("OpenDataSetDialog_Browse"));
    _pnlFile.add(_btnBrowse, BorderLayout.EAST);

    DefaultListModel model = new DefaultListModel();

    for (Pair<String, String> datasetInfo : datasetIndexData) {
        model.addElement(datasetInfo);
    }

    _listDatasetIndex.setModel(model);
    _listDatasetIndex.setCellRenderer(new DatasetIndexCellRenderer());

    _listDatasetIndex.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // Clear any filename in the text field if an item is selected
            // from the text box.
            _txtFldFileName.setText(null);
        }
    });

    _startBrowseDirectory = startBrowseDirectory;
}

From source file:BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    // Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    // LEFT COLUMN
    // Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    // Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    // RIGHT COLUMN
    // Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    // Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    // Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setVisibleRowCount(-1);/*from w  w  w .  jav  a 2 s .  co m*/
    list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    list.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) list.getModel();
            int index = dl.getIndex();
            boolean insert = dl.isInsert();
            // Get the current string under the drop.
            String value = (String) listModel.getElementAt(index);

            // 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;
            }

            // Display a dialog with the drop information.
            String dropValue = "\"" + data + "\" dropped ";
            if (dl.isInsert()) {
                if (dl.getIndex() == 0) {
                    displayDropLocation(dropValue + "at beginning of list");
                } else if (dl.getIndex() >= list.getModel().getSize()) {
                    displayDropLocation(dropValue + "at end of list");
                } else {
                    String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1);
                    String value2 = (String) list.getModel().getElementAt(dl.getIndex());
                    displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\"");
                }
            } else {
                displayDropLocation(dropValue + "on top of " + "\"" + value + "\"");
            }

            /**
             * This is commented out for the basicdemo.html tutorial page. * If you
             * add this code snippet back and delete the * "return false;" line, the
             * list will accept drops * of type string. // Perform the actual
             * import. if (insert) { listModel.add(index, data); } else {
             * listModel.set(index, data); } return true;
             */
            return false;
        }

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

        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());
        }
    });
    list.setDropMode(DropMode.ON_OR_INSERT);

    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    // Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    // Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

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

void reloadTemplateList() {
    DefaultListModel templateListModel = new DefaultListModel();
    for (Entry<Object, Object> entry : prop.entrySet()) {
        templateListModel.addElement(entry);
    }/*  ww  w. j a v  a  2 s .c o m*/
    templateList.setModel(templateListModel);
}

From source file:ListInput.java

public void appendResultSet(ResultSet results, int index, boolean toTitleCase) {
    textfield.setText("");
    DefaultListModel model = new DefaultListModel();
    try {//from   w ww  .  j  av  a  2s .  c  o  m
        while (results.next()) {
            String str = results.getString(index);
            if (toTitleCase) {
                str = Character.toUpperCase(str.charAt(0)) + str.substring(1);
            }

            model.addElement(str);
        }
    } catch (SQLException ex) {
        System.err.println("appendResultSet: " + ex.toString());
    }
    list.setModel(model);
    if (model.getSize() > 0)
        list.setSelectedIndex(0);
}

From source file:misc.TextBatchPrintingDemo.java

/**
 * Create and display the main application frame.
 *///w w w. j  a va 2s . c om
void createAndShowGUI() {
    messageArea = new JLabel(defaultMessage);

    selectedPages = new JList(new DefaultListModel());
    selectedPages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    selectedPages.addListSelectionListener(this);

    setPage(homePage);

    JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(pageItem),
            new JScrollPane(selectedPages));

    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);

    /** Menu item and keyboard shortcuts for the "add page" command.  */
    fileMenu.add(createMenuItem(new AbstractAction("Add Page") {
        public void actionPerformed(ActionEvent e) {
            DefaultListModel pages = (DefaultListModel) selectedPages.getModel();
            pages.addElement(pageItem);
            selectedPages.setSelectedIndex(pages.getSize() - 1);
        }
    }, KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK)));

    /** Menu item and keyboard shortcuts for the "print selected" command.*/
    fileMenu.add(createMenuItem(new AbstractAction("Print Selected") {
        public void actionPerformed(ActionEvent e) {
            printSelectedPages();
        }
    }, KeyEvent.VK_P, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK)));

    /** Menu item and keyboard shortcuts for the "clear selected" command.*/
    fileMenu.add(createMenuItem(new AbstractAction("Clear Selected") {
        public void actionPerformed(ActionEvent e) {
            DefaultListModel pages = (DefaultListModel) selectedPages.getModel();
            pages.removeAllElements();
        }
    }, KeyEvent.VK_C, KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK)));

    fileMenu.addSeparator();

    /** Menu item and keyboard shortcuts for the "home page" command.  */
    fileMenu.add(createMenuItem(new AbstractAction("Home Page") {
        public void actionPerformed(ActionEvent e) {
            setPage(homePage);
        }
    }, KeyEvent.VK_H, KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.ALT_MASK)));

    /** Menu item and keyboard shortcuts for the "quit" command.  */
    fileMenu.add(createMenuItem(new AbstractAction("Quit") {
        public void actionPerformed(ActionEvent e) {
            for (Window w : Window.getWindows()) {
                w.dispose();
            }
        }
    }, KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK)));

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);

    JPanel contentPane = new JPanel();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    contentPane.add(pane);
    contentPane.add(messageArea);

    JFrame frame = new JFrame("Text Batch Printing Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(menuBar);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    if (printService == null) {
        // Actual printing is not possible, issue a warning message.
        JOptionPane.showMessageDialog(frame, "No default print service", "Print Service Alert",
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:edu.ku.brc.af.tasks.subpane.formeditor.RowColDefPanel.java

/**
 * @param defStr/*from w  w  w.  j  a v a2s. c  o m*/
 * @param isRow
 */
public RowColDefPanel(final FormViewDef.JGDefItem item, final int numInUse, final boolean isRow) {
    super(new BorderLayout());

    this.isRow = isRow;

    createUI(numInUse, isRow);

    DefaultListModel model = (DefaultListModel) itemList.getModel();
    int cnt = 0;
    for (String tok : StringUtils.split(item.getDefStr(), ",")) //$NON-NLS-1$
    {
        JGoodiesDefItem jgItem = new JGoodiesDefItem(tok, isRow);
        jgItem.setInUse(cnt < numInUse);
        items.add(jgItem);
        model.addElement(jgItem);
        cnt++;
    }
}

From source file:kenh.xscript.elements.Debug.java

private void initial(Container c) {
    c.setLayout(new BorderLayout());

    // Add variable list

    DefaultListModel<String> model = new DefaultListModel();

    if (this.getEnvironment() != null) {
        java.util.Set<String> keys = this.getEnvironment().getVariables().keySet();
        for (String key : keys) {
            model.addElement(key);
        }/*from   w  w  w .  j ava 2s  . c  om*/
    } else {
        for (int i = 1; i < 10; i++) {
            model.addElement("Variable " + i);
        }
        model.addElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    }

    JList list = new JList(model);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane listPane = new JScrollPane();
    listPane.setViewportView(list);
    listPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    c.add(listPane, BorderLayout.EAST);

    list.setPreferredSize(new Dimension(150, list.getPreferredSize().height));

    // 

    JTextField quote = new JTextField();
    quote.requestFocus();

    //JButton button = new JButton(">>");

    JPanel quotePanel = new JPanel();
    quotePanel.setLayout(new BorderLayout());
    quotePanel.add(quote, BorderLayout.CENTER);
    //quotePanel.add(button, BorderLayout.EAST);

    JTextArea result = new JTextArea();
    result.setEditable(false);

    JScrollPane resultPane = new JScrollPane();
    resultPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    resultPane.setViewportView(result);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(quotePanel, BorderLayout.NORTH);
    panel.add(resultPane, BorderLayout.CENTER);

    c.add(panel, BorderLayout.CENTER);

    list.addListSelectionListener(this);
    //button.addActionListener(this);
    quote.addKeyListener(this);

    this.result = result;
}

From source file:brainflow.app.presentation.controls.FileObjectGroupSelector.java

private void updateFileList() {

    String pattern = regexField.getText();
    if (pattern.equals("")) {
        return;/*from ww w  .j  av  a  2s  . com*/
    }

    if (searchType.getSelectedItem() == GLOB) {
        pattern = FileObjectGroupSelector.globToRegexPattern(pattern);
    }

    if (!pattern.startsWith(".*")) {
        pattern = ".*" + pattern;
    }

    java.util.List<FileExplorer.FileObjectNode> fileNodes = explorer.getSelectedNodes();
    java.util.List<FileObject> matchList = new ArrayList<FileObject>();
    //System.out.println("fileNodes.size() " + fileNodes.size());
    for (FileExplorer.FileObjectNode node : fileNodes) {
        matchChildren(node, pattern, matchList, 0);

    }

    DefaultListModel listModel = new DefaultListModel();
    for (int i = 0; i < matchList.size(); i++) {
        listModel.addElement(unambiguousIdentifier(i, matchList));

    }

    fileList.setModel(listModel);

}

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

private void jButton1ActionPerformed(ActionEvent evt) {
    File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog().getApproveSelectedFile();
    if (file != null) {
        DefaultListModel model = (DefaultListModel) jarFileDirs.getModel();
        model.addElement(file);
    }/*from w w  w .  j  av a 2 s .  c o m*/
}

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

/**
 * @param uif//  w  w w.jav a  2s .c  o  m
 * @param isNew
 */
protected void editFormatter(final UIFieldFormatterIFace uif, final boolean isNew) {
    try {
        UIFieldFormatterIFace tempCopy = isNew ? uif : (UIFieldFormatterIFace) uif.clone();
        boolean isDefault = tempCopy.isDefault();

        UIFormatterEditorDlg dlg = new UIFormatterEditorDlg(this, fieldInfo, tempCopy, isNew, doProcessSamples,
                uiFieldFormatterMgrCache);
        dlg.setVisible(true);
        if (!dlg.isCancelled()) {
            UIFieldFormatterIFace selectedUIF = dlg.getSelectedFormat();
            selectedUIF.setDefault(isDefault);

            if (selectedUIF.isIncrementer() && selectedUIF.getAutoNumber() == null) {

                AutoNumberIFace autoNum = UIFieldFormatterMgr.getInstance().createAutoNumber(
                        AutoNumberGeneric.class.getName(), fieldInfo.getTableInfo().getClassName(),
                        fieldInfo.getName(), tempCopy.getFields().size() == 1);
                selectedUIF.setAutoNumber(autoNum);
            }

            DefaultListModel model = (DefaultListModel) formatList.getModel();
            if (isNew) {
                model.addElement(selectedUIF);
                uiFieldFormatterMgrCache.addFormatter(selectedUIF);
                if (model.size() == 1) {
                    selectedUIF.setDefault(true);
                    formatList.setSelectedValue(selectedUIF, true);
                }

            } else {
                model.removeElement(uif);
                model.addElement(selectedUIF);
                uiFieldFormatterMgrCache.removeFormatter(uif);
                uiFieldFormatterMgrCache.addFormatter(selectedUIF);
            }
            setHasChanged(true);

        }

    } catch (Exception ex) {
        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(UIFormatterListEdtDlg.class, ex);
    }
}