Example usage for javax.swing JList setSelectionMode

List of usage examples for javax.swing JList setSelectionMode

Introduction

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

Prototype

@BeanProperty(bound = false, enumerationValues = { "ListSelectionModel.SINGLE_SELECTION",
        "ListSelectionModel.SINGLE_INTERVAL_SELECTION",
        "ListSelectionModel.MULTIPLE_INTERVAL_SELECTION" }, description = "The selection mode.")
public void setSelectionMode(int selectionMode) 

Source Link

Document

Sets the selection mode for the list.

Usage

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList list = new JList(new CheckListItem[] { new CheckListItem("apple"), new CheckListItem("orange"),
            new CheckListItem("mango"), new CheckListItem("mango"), new CheckListItem("mango"),
            new CheckListItem("mango"), new CheckListItem("mango"), new CheckListItem("mango"),
            new CheckListItem("mango"), new CheckListItem("mango"), new CheckListItem("mango"),

            new CheckListItem("paw paw"), new CheckListItem("banana") });
    list.setCellRenderer(new CheckListRenderer());
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.addMouseListener(new MouseAdapter() {
        @Override/*from  w w  w.  j  a  va  2  s.com*/
        public void mouseClicked(MouseEvent event) {
            JList list = (JList) event.getSource();
            int index = list.locationToIndex(event.getPoint());// Get index of item
                                                               // clicked
            CheckListItem item = (CheckListItem) list.getModel().getElementAt(index);
            item.setSelected(!item.isSelected()); // Toggle selected state
            list.repaint(list.getCellBounds(index, index));// Repaint cell
        }
    });
    frame.getContentPane().add(new JScrollPane(list));
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    final DefaultListModel<String> model = new DefaultListModel<>();
    final JList<String> list = new JList<>(model);
    JFrame f = new JFrame();

    model.addElement("A");
    model.addElement("B");
    model.addElement("C");
    model.addElement("D");
    model.addElement("E");

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    JPanel leftPanel = new JPanel();
    JPanel rightPanel = new JPanel();

    leftPanel.setLayout(new BorderLayout());
    rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    list.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int index = list.locationToIndex(e.getPoint());
                Object item = model.getElementAt(index);
                String text = JOptionPane.showInputDialog("Rename item", item);
                String newitem = "";
                if (text != null)
                    newitem = text.trim();
                else
                    return;

                if (!newitem.isEmpty()) {
                    model.remove(index);
                    model.add(index, newitem);
                    ListSelectionModel selmodel = list.getSelectionModel();
                    selmodel.setLeadSelectionIndex(index);
                }// w ww. j a  v a 2s .  c o  m
            }
        }
    });
    leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    leftPanel.add(new JScrollPane(list));

    JButton removeall = new JButton("Remove All");
    JButton add = new JButton("Add");
    JButton rename = new JButton("Rename");
    JButton delete = new JButton("Delete");

    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = JOptionPane.showInputDialog("Add a new item");
            String item = null;

            if (text != null)
                item = text.trim();
            else
                return;

            if (!item.isEmpty())
                model.addElement(item);
        }
    });

    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index >= 0)
                model.remove(index);
        }

    });

    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index == -1)
                return;
            Object item = model.getElementAt(index);
            String text = JOptionPane.showInputDialog("Rename item", item);
            String newitem = null;

            if (text != null) {
                newitem = text.trim();
            } else
                return;

            if (!newitem.isEmpty()) {
                model.remove(index);
                model.add(index, newitem);
            }
        }
    });

    removeall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model.clear();
        }
    });

    rightPanel.add(add);
    rightPanel.add(rename);
    rightPanel.add(delete);
    rightPanel.add(removeall);

    rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));

    panel.add(leftPanel);
    panel.add(rightPanel);

    f.add(panel);

    f.setSize(350, 250);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

}

From source file:List.java

public static void main(String[] args) {
    final DefaultListModel model = new DefaultListModel();
    final JList list = new JList(model);
    JFrame f = new JFrame();
    f.setTitle("JList models");

    model.addElement("A");
    model.addElement("B");
    model.addElement("C");
    model.addElement("D");
    model.addElement("E");

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    JPanel leftPanel = new JPanel();
    JPanel rightPanel = new JPanel();

    leftPanel.setLayout(new BorderLayout());
    rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    list.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int index = list.locationToIndex(e.getPoint());
                Object item = model.getElementAt(index);
                String text = JOptionPane.showInputDialog("Rename item", item);
                String newitem = "";
                if (text != null)
                    newitem = text.trim();
                else
                    return;

                if (!newitem.isEmpty()) {
                    model.remove(index);
                    model.add(index, newitem);
                    ListSelectionModel selmodel = list.getSelectionModel();
                    selmodel.setLeadSelectionIndex(index);
                }/*from  w  w w  .  j  av  a2  s  . co  m*/
            }
        }
    });
    leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    leftPanel.add(new JScrollPane(list));

    JButton removeall = new JButton("Remove All");
    JButton add = new JButton("Add");
    JButton rename = new JButton("Rename");
    JButton delete = new JButton("Delete");

    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = JOptionPane.showInputDialog("Add a new item");
            String item = null;

            if (text != null)
                item = text.trim();
            else
                return;

            if (!item.isEmpty())
                model.addElement(item);
        }
    });

    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index >= 0)
                model.remove(index);
        }

    });

    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index == -1)
                return;
            Object item = model.getElementAt(index);
            String text = JOptionPane.showInputDialog("Rename item", item);
            String newitem = null;

            if (text != null) {
                newitem = text.trim();
            } else
                return;

            if (!newitem.isEmpty()) {
                model.remove(index);
                model.add(index, newitem);
            }
        }
    });

    removeall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model.clear();
        }
    });

    rightPanel.add(add);
    rightPanel.add(rename);
    rightPanel.add(delete);
    rightPanel.add(removeall);

    rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));

    panel.add(leftPanel);
    panel.add(rightPanel);

    f.add(panel);

    f.setSize(350, 250);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

}

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);/* w  w  w  .  j  av a2 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);
}

From source file:LongListTest.java

public LongListTest() {
    setTitle("LongListTest");
    setSize(400, 300);// w  ww.j  a  v  a2s . c  om
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    JList wordList = new JList(new WordListModel(300000));
    wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    wordList.setFixedCellWidth(50);
    wordList.setFixedCellHeight(15);

    JScrollPane scrollPane = new JScrollPane(wordList);

    JPanel p = new JPanel();
    p.add(scrollPane);
    wordList.addListSelectionListener(this);

    getContentPane().add(p, "Center");

    getContentPane().add(label, "North");
}

From source file:ListDrop.java

public ListDrop() {
    JFrame f = new JFrame();
    JList list = new JList(model);
    list.setDropMode(DropMode.INSERT);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setTransferHandler(new ListHandler());

    field.setDragEnabled(true);//from w  w  w .  ja v  a2 s . co m
    f.setLayout(new FlowLayout());
    f.add(new JScrollPane(list));
    f.add(field);
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
}

From source file:Main.java

public ListRenderingFrame() {
    setTitle("ListRendering");
    setSize(400, 300);/*from   w  w  w .  j  a v a2 s  .c o  m*/
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    Vector fonts = new Vector();
    fonts.add(new Font("Serif", Font.PLAIN, 8));
    fonts.add(new Font("SansSerif", Font.BOLD, 12));
    fonts.add(new Font("Monospaced", Font.PLAIN, 16));
    fonts.add(new Font("Dialog", Font.ITALIC, 12));
    fonts.add(new Font("DialogInput", Font.PLAIN, 12));
    JList fontList = new JList(fonts);
    fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    fontList.setCellRenderer(new FontCellRenderer());
    JScrollPane scrollPane = new JScrollPane(fontList);

    JPanel p = new JPanel();
    p.add(scrollPane);
    fontList.addListSelectionListener(this);

    getContentPane().add(p, "Center");

    getContentPane().add(label, "South");
}

From source file:latexstudio.editor.DbxFileActions.java

/**
 * Shows a .tex files list from user's dropbox and opens the selected one
 *
 * @return List, that contatins user's .tex files from his dropbox; can be
 * empty/*from  w  w w. j a va  2 s  .c om*/
 */
public void openFromDropbox(DropboxRevisionsTopComponent drtc, RevisionDisplayTopComponent revtc) {
    List<DbxEntryDto> dbxEntries = getDbxTexEntries(DbxUtil.getDbxClient());

    if (!dbxEntries.isEmpty()) {
        JList<DbxEntryDto> list = new JList(dbxEntries.toArray());
        list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
        int option = JOptionPane.showConfirmDialog(null, list, "Open file from Dropbox",
                JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION && !list.isSelectionEmpty()) {
            DbxEntryDto entry = list.getSelectedValue();
            String localPath = ApplicationUtils.getAppDirectory() + File.separator + entry.getName();
            File outputFile = DbxUtil.downloadRemoteFile(entry, localPath);

            revtc.close();

            drtc.updateRevisionsList(entry.getPath());
            drtc.open();
            drtc.requestActive();

            String content = FileService.readFromFile(outputFile.getAbsolutePath());
            etc.setEditorContent(content);
            etc.setCurrentFile(outputFile);
            etc.setDbxState(new DbxState(entry.getPath(), entry.getRevision()));
            etc.setModified(false);
            etc.setPreviewDisplayed(false);
        }
    } else {
        JOptionPane.showMessageDialog(etc, "No .tex files found!", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.gumtree.vis.awt.AbstractPlotEditor.java

private JPanel createHelpPanel() {
    JPanel wrap = new JPanel(new GridLayout(1, 1));

    JPanel helpPanel = new JPanel(new GridLayout(1, 1));
    helpPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    //       helpPanel.setBorder(BorderFactory.createTitledBorder(
    //            BorderFactory.createEtchedBorder(), "Help Topics"));

    SpringLayout spring = new SpringLayout();
    JPanel inner = new JPanel(spring);
    inner.setBorder(BorderFactory.createEmptyBorder());

    final IHelpProvider provider = plot.getHelpProvider();
    final JList list = new JList(provider.getHelpMap().keySet().toArray());
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //      list.setBorder(BorderFactory.createEtchedBorder());
    JScrollPane listPane1 = new JScrollPane(list);
    inner.add(listPane1);/*from  ww w  .  ja  va2 s.  c o m*/
    listPane1.setMaximumSize(new Dimension(140, 0));
    listPane1.setMinimumSize(new Dimension(70, 0));
    //      JPanel contentPanel = new JPanel(new GridLayout(2, 1));
    //      inner.add(list);
    final JTextField keyField = new JTextField();
    keyField.setMaximumSize(new Dimension(400, 20));
    keyField.setEditable(false);
    //      keyField.setMaximumSize();
    //      keyArea.setLineWrap(true);
    //      keyArea.setWrapStyleWord(true);
    //      keyArea.setBorder(BorderFactory.createEtchedBorder());
    inner.add(keyField);
    //      contentPanel.add(new JLabel());
    //      contentPanel.add(new JLabel());
    final JTextArea helpArea = new JTextArea();
    JScrollPane areaPane = new JScrollPane(helpArea);
    helpArea.setEditable(false);
    helpArea.setLineWrap(true);
    helpArea.setWrapStyleWord(true);
    //      helpArea.setBorder(BorderFactory.createEtchedBorder());
    inner.add(areaPane);
    //      contentPanel.add(new JLabel());
    //      contentPanel.add(new JLabel());
    //      inner.add(contentPanel);
    spring.putConstraint(SpringLayout.WEST, listPane1, 2, SpringLayout.WEST, inner);
    spring.putConstraint(SpringLayout.NORTH, listPane1, 2, SpringLayout.NORTH, inner);
    spring.putConstraint(SpringLayout.WEST, keyField, 4, SpringLayout.EAST, listPane1);
    spring.putConstraint(SpringLayout.NORTH, keyField, 2, SpringLayout.NORTH, inner);
    spring.putConstraint(SpringLayout.EAST, inner, 2, SpringLayout.EAST, keyField);
    spring.putConstraint(SpringLayout.WEST, areaPane, 4, SpringLayout.EAST, listPane1);
    spring.putConstraint(SpringLayout.NORTH, areaPane, 4, SpringLayout.SOUTH, keyField);
    spring.putConstraint(SpringLayout.EAST, areaPane, -2, SpringLayout.EAST, inner);
    spring.putConstraint(SpringLayout.SOUTH, inner, 2, SpringLayout.SOUTH, areaPane);
    spring.putConstraint(SpringLayout.SOUTH, listPane1, -2, SpringLayout.SOUTH, inner);

    list.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            Object[] selected = list.getSelectedValues();
            if (selected.length >= 0) {
                HelpObject help = provider.getHelpMap().get(selected[0]);
                if (help != null) {
                    keyField.setText(help.getKey());
                    helpArea.setText(help.getDiscription());
                }
            }
        }
    });

    helpPanel.add(inner, BorderLayout.NORTH);
    wrap.setName("Help");

    wrap.add(helpPanel, BorderLayout.NORTH);
    return wrap;
}

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);//w  w  w.  ja  v a  2  s.  c o  m
        }
    } 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;
}