Java Tutorial/Swing/JList Model
Содержание
- 1 Adding and Removing an Item in a JList Component
- 2 Append an item
- 3 Create a list that allows adds and removes
- 4 DefaultListModel and JList
- 5 extends AbstractListModel
- 6 extends DefaultListModel
- 7 Getting the Items in a JList Component
- 8 Insert an item at the beginning
- 9 JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.
- 10 Methods are used to remove items
- 11 Set method replaces an item
- 12 SortedListModel: sortable JList
Adding and Removing an Item in a JList Component
<source lang="java">
import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {
public static void main(String[] argv) throws Exception { DefaultListModel model = new DefaultListModel(); JList list = new JList(model); // Initialize the list with items String[] items = { "A", "B", "C", "D" }; for (int i = 0; i < items.length; i++) { model.add(i, items[i]); } }
}</source>
Append an item
<source lang="java">
import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {
public static void main(String[] argv) throws Exception { // Create a list that allows adds and removes DefaultListModel model = new DefaultListModel(); JList list = new JList(model); int pos = list.getModel().getSize(); model.add(pos, "E"); }
}</source>
Create a list that allows adds and removes
<source lang="java">
import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {
public static void main(String[] argv) throws Exception { DefaultListModel model = new DefaultListModel(); JList list = new JList(model); int pos = 0; model.add(pos, "a"); }
}</source>
DefaultListModel and JList
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.awt.BorderLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /* ListDemo.java requires no other files. */ public class ListDemo extends JPanel implements ListSelectionListener {
private JList list; private DefaultListModel listModel; private static final String hireString = "Hire"; private static final String fireString = "Fire"; private JButton fireButton; private JTextField employeeName; public ListDemo() { super(new BorderLayout()); listModel = new DefaultListModel(); listModel.addElement("Debbie Scott"); listModel.addElement("Scott Hommel"); listModel.addElement("Sharon Zakhour"); // Create the list and put it in a scroll pane. list = new JList(listModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); list.addListSelectionListener(this); list.setVisibleRowCount(5); JScrollPane listScrollPane = new JScrollPane(list); JButton hireButton = new JButton(hireString); HireListener hireListener = new HireListener(hireButton); hireButton.setActionCommand(hireString); hireButton.addActionListener(hireListener); hireButton.setEnabled(false); fireButton = new JButton(fireString); fireButton.setActionCommand(fireString); fireButton.addActionListener(new FireListener()); employeeName = new JTextField(10); employeeName.addActionListener(hireListener); employeeName.getDocument().addDocumentListener(hireListener); String name = listModel.getElementAt(list.getSelectedIndex()).toString(); // Create a panel that uses BoxLayout. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.add(fireButton); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(new JSeparator(SwingConstants.VERTICAL)); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(employeeName); buttonPane.add(hireButton); buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); add(listScrollPane, BorderLayout.CENTER); add(buttonPane, BorderLayout.PAGE_END); } class FireListener implements ActionListener { public void actionPerformed(ActionEvent e) { // This method can be called only if // there"s a valid selection // so go ahead and remove whatever"s selected. int index = list.getSelectedIndex(); listModel.remove(index); int size = listModel.getSize(); if (size == 0) { // Nobody"s left, disable firing. fireButton.setEnabled(false); } else { // Select an index. if (index == listModel.getSize()) { // removed item in last position index--; } list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } } } // This listener is shared by the text field and the hire button. class HireListener implements ActionListener, DocumentListener { private boolean alreadyEnabled = false; private JButton button; public HireListener(JButton button) { this.button = button; } // Required by ActionListener. public void actionPerformed(ActionEvent e) { String name = employeeName.getText(); // User didn"t type in a unique name... if (name.equals("") || alreadyInList(name)) { Toolkit.getDefaultToolkit().beep(); employeeName.requestFocusInWindow(); employeeName.selectAll(); return; } int index = list.getSelectedIndex(); // get selected index if (index == -1) { // no selection, so insert at beginning index = 0; } else { // add after the selected item index++; } listModel.insertElementAt(employeeName.getText(), index); // If we just wanted to add to the end, we"d do this: // listModel.addElement(employeeName.getText()); // Reset the text field. employeeName.requestFocusInWindow(); employeeName.setText(""); // Select the new item and make it visible. list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } // This method tests for string equality. You could certainly // get more sophisticated about the algorithm. For example, // you might want to ignore white space and capitalization. protected boolean alreadyInList(String name) { return listModel.contains(name); } // Required by DocumentListener. public void insertUpdate(DocumentEvent e) { enableButton(); } // Required by DocumentListener. public void removeUpdate(DocumentEvent e) { handleEmptyTextField(e); } // Required by DocumentListener. public void changedUpdate(DocumentEvent e) { if (!handleEmptyTextField(e)) { enableButton(); } } private void enableButton() { if (!alreadyEnabled) { button.setEnabled(true); } } private boolean handleEmptyTextField(DocumentEvent e) { if (e.getDocument().getLength() <= 0) { button.setEnabled(false); alreadyEnabled = false; return true; } return false; } } // This method is required by ListSelectionListener. public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -1) { // No selection, disable fire button. fireButton.setEnabled(false); } else { // Selection, enable the fire button. fireButton.setEnabled(true); } } } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { // Create and set up the window. JFrame frame = new JFrame("ListDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. JComponent newContentPane = new ListDemo(); newContentPane.setOpaque(true); // content panes must be opaque frame.setContentPane(newContentPane); // Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { // Schedule a job for the event-dispatching thread: // creating and showing this application"s GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
}</source>
extends AbstractListModel
<source lang="java">
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; public class JBenchFrame extends JFrame {
BorderLayout borderLayout1 = new BorderLayout(); JList list1 = new JList(); JButton fillButton = new JButton(); public static void main(String[] args) { JBenchFrame bm = new JBenchFrame(); } public JBenchFrame() { this.getContentPane().setLayout(borderLayout1); this.setSize(new Dimension(400, 300)); fillButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ListData ld = new ListData(); long tmStart = System.currentTimeMillis(); list1.setModel(ld); list1.repaint(); long tmEnd = System.currentTimeMillis(); System.out.println(tmEnd - tmStart); } }); fillButton.setText("Fill"); this.getContentPane().add(new JScrollPane(list1), BorderLayout.CENTER); this.getContentPane().add(fillButton, BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }
} class ListData extends AbstractListModel {
String[] strings = new String[10000]; public ListData() { for (int i = 0; i < 10000; i++) { strings[i] = "bob" + i; } } public int getSize() { return strings.length; } public Object getElementAt(int index) { return strings[index]; }
}</source>
extends DefaultListModel
<source lang="java">
import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; class MyListModel extends DefaultListModel {
protected int[] count = new int[100]; public Object getElementAt(int index) { if (index < 100) { count[index]++; } return super.elementAt(index); } public void dump() { for (int i = 0; i < 100; i++) { if (count[i] != 0) { System.out.println(i + "\t" + count[i] + "\t\t" + elementAt(i)); } } }
} public class Main extends JFrame {
MyListModel model = new MyListModel(); public Main() { for (int i = 0; i < 25; i++) { model.addElement("A" + i); } JList list = new JList(model); getContentPane().add(new JScrollPane(list), BorderLayout.CENTER); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { model.dump(); System.exit(0); } }); pack(); setVisible(true); } public static void main(String arg[]) { new Main(); }
}</source>
Getting the Items in a JList Component
<source lang="java">
import javax.swing.JList; public class Main {
public static void main(String[] argv) throws Exception { String[] items = { "A", "B", "C", "D" }; JList list = new JList(items); // Get number of items in the list int size = list.getModel().getSize(); // 4 // Get all item objects for (int i = 0; i < size; i++) { Object item = list.getModel().getElementAt(i); } }
}</source>
Insert an item at the beginning
<source lang="java">
import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {
public static void main(String[] argv) throws Exception { DefaultListModel model = new DefaultListModel(); JList list = new JList(model); int pos = 0; model.add(pos, "a"); }
}</source>
JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.
<source lang="java">
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; public class List {
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); } } } }); 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); }
}</source>
Methods are used to remove items
<source lang="java">
import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {
public static void main(String[] argv) throws Exception { DefaultListModel model = new DefaultListModel(); JList list = new JList(model); // Remove the first item int pos = 0; model.remove(pos); // Remove the last item pos = model.getSize() - 1; if (pos >= 0) { model.remove(pos); } // Remove all items model.clear(); }
}</source>
Set method replaces an item
<source lang="java">
import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {
public static void main(String[] argv) throws Exception { DefaultListModel model = new DefaultListModel(); JList list = new JList(model); // Replace the 2nd item int pos = 1; model.set(pos, "b"); }
}</source>
SortedListModel: sortable JList
<source lang="java">
import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.*; import java.util.*; class SortedListModel extends AbstractListModel {
SortedSet<Object> model; public SortedListModel() { model = new TreeSet<Object>(); } public int getSize() { return model.size(); } public Object getElementAt(int index) { return model.toArray()[index]; } public void add(Object element) { if (model.add(element)) { fireContentsChanged(this, 0, getSize()); }
}
public void addAll(Object elements[]) { Collection<Object> c = Arrays.asList(elements); model.addAll(c); fireContentsChanged(this, 0, getSize()); } public void clear() { model.clear(); fireContentsChanged(this, 0, getSize()); } public boolean contains(Object element) { return model.contains(element); } public Object firstElement() { return model.first(); } public Iterator iterator() { return model.iterator(); } public Object lastElement() { return model.last(); } public boolean removeElement(Object element) { boolean removed = model.remove(element); if (removed) { fireContentsChanged(this, 0, getSize()); } return removed; }
}
public class JListLocationToIndexSample {
public static void main(String args[]) { SortedListModel model = new SortedListModel(); model.add("A"); model.add("C"); model.add("Z"); model.add("B"); JFrame frame = new JFrame("Selecting JList"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JList jlist = new JList(model); JScrollPane scrollPane1 = new JScrollPane(jlist); frame.add(scrollPane1, BorderLayout.CENTER); frame.setSize(350, 200); frame.setVisible(true); }
}</source>