【问题标题】:Using JList with Ordered Array Lists将 JList 与有序数组列表一起使用
【发布时间】:2014-06-30 12:30:31
【问题描述】:

我很难将列表中的元素显示到我的 GUI 的 JList 上。我尝试了 JDK 附带的 addElement 和其他一些样式的 JList 方法,但我无法按照我想要的方式工作。

我正在尝试在 JList 上显示输入字符串,然后将它们存储在我的单独列表中以供调用。以这种方式使用 JList 和 JFrame 时是否有首选方法?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PlaylistMakerFinal extends JFrame implements ActionListener{

private static int SIZE = 1000;
private static int WIDTH = 600;
private static int HEIGHT = 600;
OrderedArrayList<String> songList = new OrderedArrayList<String>(SIZE);
{
    songList = new OrderedArrayList<String>();
}

private JButton deleteButton;
private JButton addButton;
private JTextField addTextField;
private JTextField searchTextField;
private JButton searchButton;
private JButton exitButton;
private JList<String> songArea;


public void displayText(){
    this.getContentPane().add(songArea);

    }

public PlaylistMakerFinal() {



    setTitle("Playlist Maker");
    Container pane = getContentPane();
    pane.setLayout(null);
    setSize(WIDTH, HEIGHT);

    songArea = new JList<String>();

    addTextField = new JTextField();

    searchTextField = new JTextField();

    exitButton = new JButton("Exit");
    exitButton.addActionListener(this);

    addButton = new JButton("Add");
    addButton.addActionListener(this);

    deleteButton = new JButton("Delete");
    deleteButton.addActionListener(this);

    searchButton = new JButton("Search");
    searchButton.addActionListener(this);


    songArea.setSize(250, 400);
    addTextField.setSize(250, 30);
    searchTextField.setSize(250, 30);
    addButton.setSize(100, 40);
    deleteButton.setSize(100, 40);
    searchButton.setSize(100, 40);
    exitButton.setSize(100, 40);

    songArea.setLocation(10, 50);
    addTextField.setLocation(10,10);
    searchTextField.setLocation(10, 480);
    addButton.setLocation(300, 5);
    deleteButton.setLocation(420, 5);
    searchButton.setLocation(300, 475);
    exitButton.setLocation(420, 475);

    pane.add(songArea);
    pane.add(addTextField);
    pane.add(searchTextField);
    pane.add(addButton);
    pane.add(deleteButton);
    pane.add(searchButton);
    pane.add(exitButton);
    setVisible(true);

}

public static void main(String args[]){
    PlaylistMakerFinal playlist = new PlaylistMakerFinal();

}

public void actionPerformed(ActionEvent e){
    JList songArea = new JList(songList.list);
    String action = e.getActionCommand();
    String addTitle;
    String deleteTitle;
    String searchTitle;
    int searchInt;
    int deleteInt;

//        Just some methods I was testing that didn't bear any fruit.
//        DefaultListModel<String> listModel;
//        listModel = new DefaultListModel<String>();
//        JList songArea = new JList(listModel);

    //Method to add a song to the list
    if(action.equals("Add")){

        addTitle = addTextField.getText();
        System.out.println("ADDED " + addTitle);

                songList.insertEnd(addTitle);
                songArea.setListData(songList.list);
//                  songArea.addElement();
    }

    //Method to remove a song from the list
    else if(action.equals("Delete")){

        deleteTitle = addTextField.getText();

    deleteInt = songList.seqSearch(deleteTitle);

    if(deleteInt != -1){
        songList.removeAt(deleteInt);
        songArea.remove(deleteInt);
        System.out.println("DELETED " + deleteTitle);
        }

    }

    //Method to search the list for a song and return an answer in a JOptionPane
    else if(action.equals("Search")){
        searchTitle = searchTextField.getText();
        searchInt = songList.seqSearch(searchTitle);

        songArea.setSelectedIndex(searchInt);

    }
    //Method to exit the program and close the window
    else if(action.equals("Exit")){
        System.exit(0);
    }
    else{

    }
}   

ArrayListADT:

}

// Generic ArrayList interface, defining all the methods an array list should have.
// Any class that implements this interface must define all the below methods,
// or just declare them as abstract.

public interface ArrayListADT<T> extends Cloneable
{
// Determine whether or not the list is empty.
public boolean isEmpty();

// Determine whether or not the list if full.
public boolean isFull();

// Return the number of elements in the list.
public int listSize();

// Return the maximum size of the list.
public int maxListSize();

// Output the elements of the list.
public void print();

// Returns a copy of objects' data in store.  
// This method clones only the references stored in the list.
// The objects themselves are not cloned.
public Object clone();

// Determine whether item is the same as the item in the list
// at location.
public boolean isItemAtEqual(int location, T item);

// Insert insertItem into the list at position location.
public void insertAt(int location, T insertItem);

// Insert insertItem at the end of the list.
public void insertEnd(T insertItem);

// Remove the item from the list at position location.
public void removeAt(int location);

// Retrieve the element from the list at position location,
// and return it.
public T retrieveAt(int location);

// Replace the element in the list at position location with repItem.
public void replaceAt(int location, T repItem);

// Remove all elements from the list.
public void clearList();

// Determine whether searchItem is in the list or not.  Return its
// location, or -1.
public int seqSearch(T searchItem);

// Remove item removeItem from the list.
public void remove(T removeItem);
}

数组列表类:

// Generic abstract ArrayList class.
// Implements ArrayListADT, so either defines or declares every method in ArrayListADT.
// Defines those methods that are generic enough to be defined.
// Left others as just abstract declarations.
// Since this class is abstract, it cannot be instantiated, but it can be declared as a reference,
// and can be used as a superclass.

public abstract class ArrayListClass<T> implements ArrayListADT<T>, Cloneable
{
// Protected member variables, inherited by any subclasses.

// The length and maximum size of the list.
protected int length;
protected int maxSize;

// The array to hold the list of any type of elements.
protected T[] list;

// Default constructor.
// Create a list size of 100, length will be 0 since it is empty.
public ArrayListClass()
{
    maxSize = 100;
    length = 0;
    list = (T[]) new Object[maxSize];
}

// Constructor.
// Create a list size of size, length will be 0 since it is empty.
public ArrayListClass(int size)
{
    // Make sure size is valid, otherwise use 100.
    if (size <= 0) 
    {
        System.err.println("The array size must be positive. Creating an array of size 100.");
        maxSize = 100;
    }
    else 
    {
        maxSize = size;
    }

    length = 0;
    list = (T[]) new Object[maxSize];
}

// Determine whether or not the list is empty.
public boolean isEmpty()
{
    // List is empty if length equals 0.
    return (length == 0);
}

// Determine whether or not the list if full.
public boolean isFull()
{
    // List is full if length equals maxSize.
    return (length == maxSize);
}

// Return the number of elements in the list.
public int listSize()
{
    return length;
}

// Return the maximum size of the list.
public int maxListSize()
{
    return maxSize;
}

// Output the elements of the list.
public void print()
{
    for (int i = 0; i < length; i++)
    {
        System.out.println(list[i].toString());
    }
    System.out.println();
}

// Returns a copy of objects' data in store.  
// This method clones only the references stored in the list.
// The objects themselves are not cloned.
public Object clone()
{
    // Declare a copy array to return.
    ArrayListClass<T> copy;

    // Now try to clone it.
    // First, just make a copy of the class as a whole (the 2 integers and the list).
    try
    {
        copy = (ArrayListClass<T>) super.clone();
    }
    catch (CloneNotSupportedException e)
    {
        return null;
    }

    // Now call clone on the list itself.  This will make a shallow copy of the 
    // list, though.  There is no way to make a deep copy of the list from here.
    // So right now, copy.list[0] points to the same object as list[0].
    copy.list = (T[]) list.clone();
    return copy;
}

// Determine whether item is the same as the item in the list
// at location.
public boolean isItemAtEqual(int location, T item)
{
    // Make sure location is valid.
    if (location < 0 || location >= length)
    {
        System.err.println("The location of the item to be compared is out of range.");
        return false;
    }

    // Now just return if the item at this location is equal to item.
    // Use the equals method of this Object.
    return (list[location].equals(item));
}

// Remove the item from the list at position location.
public void removeAt(int location)
{
    // Make sure location is valid.
    if (location < 0 || location >= length)
    {
        System.err.println("The location of the item to be removed is out of range.");
    }
    else
    {
        // Shift everything in the list from location to the end over one element to the left.
        // Run over what was in location, shifting the whole list over one.
        for (int i = location; i < length - 1; i++)
        {
            list[i] = list[i + 1];
        }

        // Take the last element out of the list now, we don't need it anymore (it was moved over one).
        // Reduce size by 1.
        list[length - 1] = null;
        length--;
    }
}

// Retrieve the element from the list at position location,
// and return it.
public T retrieveAt(int location)
{
    // Make sure location is valid.
    if (location < 0 || location >= length)
    {
        System.err.println("The location of the item to be retrieved is out of range.");
        return null;
    }

    // Now just return the item at that location.
    return list[location];
}

// Remove all elements from the list.
public void clearList()
{
    // Set everything in the list to null.
    for (int i = 0; i < length; i++)
    {
        list[i] = null;
    }

    length = 0;

    // Do garbage collection to clean up all the objects out there that
    // no longer have references in the list.
    System.gc();
}

// Abstract methods, have no definition here, must be defined by subclasses.


//Search for the minimum value in the list
public abstract <T extends Comparable<T>> T minimum();

//Search for the maximum value in the list
public abstract <T extends Comparable<T>> T maximum();


// Insert insertItem into the list at position location.
public abstract void insertAt(int location, T insertItem);

// Insert insertItem at the end of the list.
public abstract void insertEnd(T insertItem);

// Replace the element in the list at position location with repItem.
public abstract void replaceAt(int location, T repItem);

// Determine whether searchItem is in the list or not.  Return its
// location, or -1.
public abstract int seqSearch(T searchItem);

// Remove item removeItem from the list.
public abstract void remove(T removeItem);
}

OrderedArrayList:

// Generic OrderedArrayList class, inherits from ArrayListClass.
// Inherits all methods from ArrayListClass, plus defines those methods that
// are abstract in ArrayListClass.
// Represents an ordered list of any type of Object.

public class OrderedArrayList<T> extends ArrayListClass<T>
{
// Default constructor.
public OrderedArrayList()
{
    super();
}

// Constructor.
public OrderedArrayList(int size)
{
    super(size);
}

// Insert insertItem into the list at the correct ordered location.
public void insert(T insertItem)
{
    int loc;
    boolean found = false;

    // Check if list is empty or full.  Insert into empty list,
    // error on full list.
    if (length == 0)
    {
        list[length++] = insertItem;
    }
    else if (length == maxSize)
    {
        System.err.println("Cannot insert in a full list.");
    }
    else
    {
        // Since the list is ordered, first find where this item needs to 
        // be inserted so the list stays ordered.
        for (loc = 0; loc < length; loc++)
        {
            Comparable<T> temp = (Comparable<T>) list[loc];
            if (temp.compareTo(insertItem) >= 0)
            {
                found = true;
                break;
            }
        }

        // If a spot for this item was not found, it must belong at the end
        // of the list.
        if (!found)
        {
            loc = length;
        }

        // Shift everything in the list from location to the end to the right,
        // to open up a new spot at location.
        for (int i = length; i > loc; i--)
        {
            list[i] = list[i - 1];
        }

        // Fill the location spot and increase length by 1.
        list[loc] = insertItem;
        length++;
    }
}

// Insert insertItem into the list at position location.
// location is actually ignored here since this list is ordered
// and the item must be inserted in its correct ordered position.
public void insertAt(int location, T insertItem)
{
    // Make sure location is valid, and that the list is not full.
    if (location < 0 || location >= maxSize)
    {
        System.err.println("The position of the item to be inserted is out of range.");
    }
    else if (length >= maxSize)
    {
        System.err.println("Cannot insert in a full list.");
    }
    else
    {
        System.out.println("This is a sorted list. Inserting at the proper place.");

        // Use insert method.
        insert(insertItem);
    }
}

// Insert insertItem at the end of the list.
public void insertEnd(T insertItem)
{
    if (length >= maxSize)
    {
        System.err.println("Cannot insert in a full list.");
    }
    else
    {
        System.out.println("This is a sorted list. Inserting at the proper place.");

        // Use insert method.
        insert(insertItem);
    }
}

// Replace the element in the list at position location with repItem.
public void replaceAt(int location, T repItem)
{
    // Make sure location is valid.
    if (location < 0 || location >= length)
    {
        System.err.println("The position of the item to be replaced is out of range.");
    }
    else
    {
        // First remove the item at this position, then insert this new
        // item in its proper ordered place.
        removeAt(location);
        insert(repItem);
    }
}

// Determine whether searchItem is in the list or not.  Return its
// location, or -1.
public int seqSearch(T searchItem)
{
    int loc;
    boolean found = false;

    // Walk through the entire list from beginning to end, looking
    // for an item in the list that is >= searchItem, because the 
    // list is ordered.  Once an item > searchItem is found, stop
    // searching.   
    for (loc = 0; loc < length; loc++)
    {
        // If searchItem is found at that location, break out of this
        // search loop.
        // Use compareTo method to compare two objects in the list, so 
        // cast them as Comparable first.           
        Comparable<T> temp = (Comparable<T>) list[loc];
        if (temp.compareTo(searchItem) >= 0)
        {
            found = true;
            break;
        }
    }

    // If found is true above in the loop, that just means the search stopped.
    // Now see if a match was actually found.
    // Otherwise return -1.
    if (found)
    {
        if (list[loc].equals(searchItem))
        {
            return loc;
        }
        else
        {
            return -1;
        }
    }
    else
    {
        return -1;
    }
}

// Remove item removeItem from the list.
public void remove(T removeItem)
{
    int loc;

    // Make sure the list has items in it.
    if (length == 0)
    {
        System.err.println("Cannot delete from an empty list.");
    }
    else
    {
        // Use seqSearch method to try to find this item first.
        loc = seqSearch(removeItem);

        // If found, use removeAt method to just remove it.
        // Otherwise, print an error, this item is not in the list.
        if (loc != -1)
        {
            removeAt(loc);
        }
        else
        {
            System.out.println("The item to be deleted is not in the list.");
        }
    }
}

@Override
public <T extends Comparable<T>> T minimum() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public <T extends Comparable<T>> T maximum() {
    // TODO Auto-generated method stub
    return null;
}
}

【问题讨论】:

  • 您能否详细说明您的程序是如何运行不正常的?在我看来,您当前的解释似乎假设我们知道您的代码在做什么。如果您可以创建并发布minimal code example program,也会更好。
  • 为什么要实施列表?您是否考虑过使用Arrays.sort() 对列表进行排序,然后使用Array.binarySearch() 来获取要插入的索引?
  • @user3294343:我猜这是作业。

标签: java swing user-interface arraylist jlist


【解决方案1】:

您正在 actionPerformed 方法内创建一个全新的 JList 并向其中添加数据,这对完全独立显示的 JList 没有影响。建议:不要创建新的 JList 对象。而是使用您拥有的 JList 或更好的模型。

更好的是基于 AbstractListModel 创建您自己的自定义 ListModel,并将您的 ArrayListClass&lt;T&gt; 或接口作为此模型的核心。然后确保通过这个模型类进行所有数据更改。

【讨论】:

    猜你喜欢
    • 2012-10-30
    • 2016-01-15
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多