Example usage for javax.swing DefaultListModel removeAllElements

List of usage examples for javax.swing DefaultListModel removeAllElements

Introduction

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

Prototype

public void removeAllElements() 

Source Link

Document

Removes all components from this list and sets its size to zero.

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);//  w w w  .ja va  2s. c o  m
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < 5; j++) {
            model.addElement(labels[j]);
        }
    }
    model.removeAllElements();

    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: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]);//from w w w . j  av  a2 s. c  om
    }
    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]);//  w  w w . j  a  va  2 s .c  om
    }
    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:de.pavloff.spark4knime.jsnippet.ui.JarListPanel.java

/**
 * Set the files to display./*from w w  w .j av a2 s.c  o  m*/
 * @param files the files
 */
public void setJarFiles(final String[] files) {
    boolean doUpdate = false;
    if (m_filesCache == null) {
        m_filesCache = files;
        doUpdate = true;
    } else {
        if (!Arrays.deepEquals(m_filesCache, files)) {
            m_filesCache = files;
            doUpdate = true;
        }
    }
    if (doUpdate) {
        DefaultListModel<String> jarListModel = (DefaultListModel<String>) m_addJarList.getModel();
        jarListModel.removeAllElements();
        for (String f : files) {
            try {
                JavaSnippetUtil.toFile(f); // validate existence etc.
                jarListModel.addElement(f);
            } catch (InvalidSettingsException e) {
                // ignore
            }
        }
    }
}

From source file:FontChooser.java

private void setListValues(JList list, String[] values) {
    if (list.getModel() instanceof DefaultListModel) {
        DefaultListModel model = (DefaultListModel) list.getModel();
        model.removeAllElements();
        for (String value : values) {
            model.addElement(value);//w  ww  .  j av a2s . c  o  m
        }
    }
}

From source file:ca.sqlpower.swingui.enterprise.client.ServerProjectsManagerPanel.java

protected void refreshInfoList() {
    DefaultListModel model = (DefaultListModel) projects.getModel();
    model.removeAllElements();

    SPServerInfo serviceInfo = getSelectedServerInfo();
    if (serviceInfo != null) {
        try {/* w  ww  .  ja  v a  2  s .c  o m*/
            List<ProjectLocation> projectLocations = getProjectLocations();

            // Sorts the project locations alphabetically
            Collections.sort(projectLocations, new Comparator<ProjectLocation>() {
                public int compare(ProjectLocation proj1, ProjectLocation proj2) {
                    return proj1.getName().compareToIgnoreCase(proj2.getName());
                }
            });

            model.clear();
            for (ProjectLocation pl : projectLocations) {
                model.addElement(pl);
            }

            connected = true;
        } catch (Exception ex) {
            model.removeAllElements();
            model.addElement("Unable to get projects from server");
            connected = false;
            upf.createUserPrompter("Server Unavailable", UserPromptType.MESSAGE, UserPromptOptions.OK,
                    UserPromptResponse.OK, "OK", "OK").promptUser("");
        }

        refreshPanel();
    } else {
        model.addElement("No Server Selected");
        connected = false;
        refreshPanel();
    }
}

From source file:ca.sqlpower.swingui.enterprise.client.ServerProjectsManagerPanel.java

/**
 * Creates a dialog that lets the user choose a server connection and then a
 * project.// w  ww  .  j  a v a  2 s . c  om
 * 
 * @param serverManager
 *            This object contains all of the server information objects
 *            known and the servers based on their information will be
 *            displayed in a list so a user can navigate to different
 *            projects in different servers.
 * @param dialogOwner
 *            The dialog to parent new dialogs to.
 * @param upf
 *            A user prompter factory for displaying error and warning
 *            messages to users.
 * @param closeAction
 *            An action that will close the dialog or frame that this dialog
 *            is contained in.
 * @param defaultFileDirectory
 *            A default file directory to start looking for files in if the
 *            user wants to upload a project. If null this will default to
 *            the user's home directory.
 * @param cookieStore
 *            A cookie store for HTTP requests. Used by the
 *            {@link ClientSideSessionUtils}.
 */
public ServerProjectsManagerPanel(SPServerInfoManager serverManager, Component dialogOwner,
        UserPrompterFactory upf, Action closeAction, File defaultFileDirectory, CookieStore cookieStore) {
    this.dialogOwner = dialogOwner;
    this.upf = upf;
    this.closeAction = closeAction;
    this.defaultFileDirectory = defaultFileDirectory;
    this.cookieStore = cookieStore;

    cookieStore.clear();

    DefaultFormBuilder builder = new DefaultFormBuilder(
            new FormLayout("pref:grow, 5dlu, pref:grow, 5dlu, pref", "pref, pref, pref"));

    servers = new JList(new DefaultListModel());
    servers.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e)) {
                refreshInfoList();
            }
        }
    });

    DefaultListModel serversModel = (DefaultListModel) servers.getModel();
    serversModel.removeAllElements();
    if (serverManager.getServers(false).size() > 0) {
        for (SPServerInfo serverInfo : serverManager.getServers(false)) {
            serversModel.addElement(serverInfo);
        }
    } else {
        serversModel.addElement("No Servers");
        servers.setEnabled(false);
    }

    projects = new JList(new DefaultListModel());
    projects.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            refreshPanel();
            if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
                getOpenAction().actionPerformed(null);
            }
        }
    });

    JScrollPane projectsPane = new JScrollPane(projects);
    projectsPane.setPreferredSize(new Dimension(250, 300));

    JScrollPane serverPane = new JScrollPane(servers);
    serverPane.setPreferredSize(new Dimension(250, 300));

    CellConstraints cc = new CellConstraints();
    builder.add(new JLabel("Servers:"), cc.xyw(1, 1, 2));
    builder.add(new JLabel("Projects:"), cc.xyw(3, 1, 2));
    builder.nextLine();
    builder.add(serverPane, cc.xywh(1, 2, 1, 2));
    builder.add(projectsPane, cc.xywh(3, 2, 1, 2));

    DefaultFormBuilder buttonBarBuilder = new DefaultFormBuilder(new FormLayout("pref"));
    buttonBarBuilder.append(new JButton(refreshAction));
    buttonBarBuilder.append(securityButton);
    buttonBarBuilder.append(new JButton(newAction));
    buttonBarBuilder.append(openButton);
    buttonBarBuilder.append(new JButton(uploadAction));
    buttonBarBuilder.append(new JButton(deleteAction));
    buttonBarBuilder.append(new JButton(closeAction));
    builder.add(buttonBarBuilder.getPanel(), cc.xy(5, 2));
    builder.setDefaultDialogBorder();
    panel = builder.getPanel();
}

From source file:imageuploader.ImgWindow.java

private void jB_RemoveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_RemoveMouseClicked
    // TODO add your handling code here:
    if (jL_Info.getSelectedIndices().length == 0) {
        JOptionPane.showMessageDialog(rootPane, "Select a color to delete");
    } else {/*from w w  w  . jav  a2s .  c  o  m*/
        DefaultListModel mod = (DefaultListModel) jL_Info.getModel();
        if (jL_Info.getSelectedIndices().length == 1) {
            int[] a = jL_Info.getSelectedIndices();
            mod.removeElementAt(a[0]);
        } else {
            mod.removeAllElements();
        }
    }
}

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

/**
 * //from   w ww. j av a2s  . c om
 */
private void doPickedNewObjType() {
    boolean hadItems = dbObjList.getModel().getSize() > 0;
    doClearAll(false);
    topLbl.setText(typeCBX.getSelectedItem().toString());

    DefaultListModel model = (DefaultListModel) recSetList.getModel();
    model.removeAllElements();
    botIdHash.clear();

    rsBtn.setEnabled(false);
    fmBtn.setEnabled(false);

    if (hadItems) {
        searchBtn.setEnabled(true);
        startBtn.setEnabled(false);
    }
}

From source file:misc.TextBatchPrintingDemo.java

/**
 * Create and display the main application frame.
 *///from   w ww.  jav a  2  s  . c o  m
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);
    }
}