从列表中删除项目/在列表中搜索项目

时间:2015-04-29 17:10:18

标签: java list

我正在一个我们有电话簿程序的实验室工作。程序打开一个框,然后打开一个包含名称和数字列表的.bat文件。

我无法弄清楚如何让我的deleteMI函数和searchMI函数工作。

非常感谢任何帮助

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.JOptionPane;

public class PhoneBook extends Frame implements ActionListener, ItemListener {

MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem searchMI, deleteMI, updateMI, newEntryMI, sortMI;
String fileName;
List nameList, numberList;
TextField lastName, firstName, phoneNumber;

/**
 * Constructor
 */
public PhoneBook() {
    super("White Pages");  // set frame title
    setLayout(new BorderLayout());  // set layout

    // create menu bar
    MenuBar menubar = new MenuBar();
    setMenuBar(menubar);

    // create file menu
    Menu fileMenu = new Menu("File");
    menubar.add(fileMenu);
    newMI = fileMenu.add(new MenuItem("New"));
    newMI.addActionListener(this);
    openMI = fileMenu.add(new MenuItem("Open"));
    openMI.addActionListener(this);
    fileMenu.addSeparator();
    saveMI = fileMenu.add(new MenuItem("Save"));
    saveAsMI = fileMenu.add(new MenuItem("Save As ..."));
    fileMenu.addSeparator();
    exitMI = fileMenu.add(new MenuItem("Exit"));
    exitMI.addActionListener(this);

    // create edit menu
    Menu editMenu = new Menu("Edit");
    menubar.add(editMenu);
    updateMI = editMenu.add(new MenuItem("Update"));
    updateMI.addActionListener(this);
    newEntryMI = editMenu.add(new MenuItem("New Entry"));
    newEntryMI.addActionListener(this);
    deleteMI = editMenu.add(new MenuItem("Delete"));
    editMenu.addSeparator();
    searchMI = editMenu.add(new MenuItem("Search"));
    searchMI.addActionListener(this);
    sortMI = editMenu.add(new MenuItem("Sort"));

    // create phone list and controls
    Panel listPanel = new Panel(new BorderLayout());
    add(listPanel, BorderLayout.CENTER);
    Label label = new Label("Name List", Label.LEFT);
    listPanel.add(label, BorderLayout.NORTH);
    nameList = new List();
    nameList.addItemListener(this);
    numberList = new List();
    listPanel.add(nameList, BorderLayout.CENTER);
    Panel panel = new Panel(new BorderLayout());
    add(panel, BorderLayout.WEST);
    Panel editPanel = new Panel(new GridLayout(6, 1));
    panel.add(editPanel, BorderLayout.NORTH);
    label = new Label("Last Name", Label.LEFT);
    editPanel.add(label);
    lastName = new TextField();
    editPanel.add(lastName);
    label = new Label("First Name", Label.LEFT);
    editPanel.add(label);
    firstName = new TextField();
    editPanel.add(firstName);
    label = new Label("Phone Number", Label.LEFT);
    editPanel.add(label);
    phoneNumber = new TextField();
    editPanel.add(phoneNumber);
}

// implementing ActionListener
public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == newMI) {
        nameList.removeAll();
        numberList.removeAll();
        fileName = null;
        display(-1);
        setTitle("White Pages");   // reset frame title
    }
    else if(source == openMI) {
        doOpen();
    }
    else if(source == exitMI) {
        System.exit(0);
    }
    else if(source == updateMI) {
        int index = nameList.getSelectedIndex();
        String name = lastName.getText().trim() + " " + firstName.getText().trim();
        String number = phoneNumber.getText().trim();
        if(index < 0) {  // add a new entry
            nameList.add(name);
            numberList.add(number);
            nameList.select(nameList.getItemCount()-1);
        }
        else {  // update an existing entry
            nameList.replaceItem(name, index);
            numberList.replaceItem(number, index);
            nameList.select(index);
        }
    }
    else if(source == newEntryMI) {
        nameList.select(-1);
        display(-1);            
    }

// Can't get delete to work     
    else if(source == deleteMI) {
        int name = nameList.getSelectedIndex();
        int number = numberList.getSelectedIndex();
       if(name >= 0){
        nameList.remove(name);
        numberList.remove(number);
       }                                                
    }


// Can't get search to work 
    else if(source == searchMI) {
        String searchName = JOptionPane.showInputDialog(this,
                            "Please enter a name (last first) to search:");
        System.out.println("Name to search: " + searchName);
        int index = nameList.getSelectedIndex();
        String name = nameList.getItem(index);
            for(int i=0; i < nameList.getItemCount(); i++){
                if(name.equalsIgnoreCase(searchName)){

                    nameList.select(index);
                    System.out.println("We Found Him");
                }        
            }          
    }

else if(source == sortMI) {
        System.exit(0);




    }  


}








/**
 * Implementing ItemListener to display the selected entry
 */
public void itemStateChanged(ItemEvent event) {
    display(nameList.getSelectedIndex());
}

/**
 * method to specify and open a file
 */
private void doOpen() {
    // display file selection dialog
    FileDialog fDialog = new FileDialog(this, "Open ...", FileDialog.LOAD);
    fDialog.setVisible(true);
    // Get the file name chosen by the user
    String file = fDialog.getFile();
    // If user canceled file selection, return without doing anything.
    if(file == null)
        return;
    fileName = fDialog.getDirectory() + file;

    // Try to create a file reader from the chosen file.
    FileReader reader;
    try {
        reader = new FileReader(fileName);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this, "File Not Found: " + fileName,
                                      "Error", JOptionPane.ERROR_MESSAGE);
        doOpen();
        return;
    }
    BufferedReader bReader = new BufferedReader(reader);
    // remove items from before if any
    nameList.removeAll();
    numberList.removeAll();
    // Try to read from the input file one line at a time.
    try {
        int index;
        String name, number;
        String textLine = bReader.readLine();
        while (textLine != null) {
            index = textLine.indexOf((int) ',');
            if(index > 0) {
                name = textLine.substring(0, index);
                number = textLine.substring(index+1);
                nameList.add(name.trim());
                numberList.add(number.trim());
            }
            textLine = bReader.readLine();
        }
        bReader.close();
        reader.close();
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(this, "Error reading file: " + ioe.toString(),
                                      "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }
    setTitle("White Pages: " +file);   // reset frame title
    nameList.select(0);
    display(0);
}

/**
 * method to display the current entry
 */
private void display(int index) {
    if(index < 0) {
        lastName.setText("");
        firstName.setText("");
        phoneNumber.setText("");
    }
    else {
        String name = nameList.getItem(index);
        int space = name.indexOf((int) ' ');
        lastName.setText(name.substring(0, space));
        firstName.setText(name.substring(space+1));
        phoneNumber.setText(numberList.getItem(index));
    }
}

/**
 * the main method
 */
public static void main(String[] argv) {
    // create frame
    System.out.println("Creating window ... ");
    PhoneBook frame = new PhoneBook();
  Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setSize(size.width/2, size.height/2);
    frame.setLocation(100, 100);

    System.out.println("Your Screen Size: " + size.width + " (width) x "
                       + size.height + " (height)");

    //Working on search functions

    String name1 = "John";
    String name2 = "James";
    if(name1.equalsIgnoreCase(name2)){
        System.out.println("The two names are the same");
    }
    else 
        System.out.println("The two names are different");

    //Working on Sort function

    String nameA = "John";
    String nameB = "James";
    if(nameA.compareToIgnoreCase(nameB) == 0) {
        System.out.println("The two names are the same");
    }
    else if (nameA.compareToIgnoreCase(nameB) < 0) 
        System.out.println("Name A comes before Name B");
    else 
        System.out.println("Name A comes after Name B");


    // add window closing listener
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    // show the frame
    frame.setVisible(true);
}

![enter image description here][1]}

1 个答案:

答案 0 :(得分:0)

两件事:

  1. 您没有向deleteMI
  2. 添加actionListener
  3. 搜索循环不正确,应为:

    else if(source == searchMI) {
        String searchName = JOptionPane.showInputDialog(this,
                "Please enter a name (last first) to search:");
        System.out.println("Name to search: " + searchName);
        String name;
        for(int i=0; i < nameList.getItemCount(); i++){
            name = nameList.getItem(i);
            if(name.equalsIgnoreCase(searchName)){
                nameList.select(i);
                    //add this code for display data:
                String[] n = name.split(" ");
                firstName.setText(n[0]);
                lastName.setText(n[1]);
                phoneNumber.setText(numberList.getItem(i));
                    //end
                System.out.println("We Found Him");
            }
        }
    }
    
  4. 但搜索仅适用于“姓氏+名字”字符串。

    您使用索引变量的方式不正确。它没有随着循环而改变。

    删除的问题由int number = numberList.getSelectedIndex();决定 - 你没有选择的项目(至少在上面的代码中,根本没有可见的numberList),所以它返回-1。它存在ArrayOutOfBoundsException。因此,实施此解决方案:

        else if(source == deleteMI) {
            int index = nameList.getSelectedIndex();
            if(index >= 0){
                nameList.remove(index);
                numberList.remove(index);
            }
        }
    

    至于排序方法,我现在可以做的就是:

        else if(source == sortMI){
            String[] list = nameList.getItems();
            String[] nums = numberList.getItems();
            Arrays.sort(list);
            Arrays.sort(nums);
            for(int i = 0; i<list.length;i++){
                nameList.replaceItem(list[i],i);
                numberList.replaceItem(nums[i],i);
            }
            nameList.revalidate();
            numberList.revalidate();
        }
    

    它不是优雅的代码,但据我所知,它的工作原理。我希望它能满足你的需求。