在ArrayLists中的对象中搜索String / Int

时间:2014-03-25 00:18:06

标签: java object search netbeans arraylist

我试图在数组(Inventory)中搜索对象(ProductInfo)中的字符串(名称)或/和整数(ID)。之后,名称,ID,编号和描述将显示在4个单独的Lable(NameOut,IDOut,Num Out,DesOut)中。我不知道如何做到这一点。任何帮助表示赞赏。

NameGo是我按名称搜索的按钮,IDGo是按ID搜索的按钮。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.*;

/**
 *
 * @author matthewmurchison
 */
public class mVentory extends javax.swing.JFrame {

    /**
     * Creates new form mVentory
     */
       public mVentory() {
        initComponents();

     }

        public class ProductInfo{
                    String name; 
                    String des; 
                    int ID; 
                    int num; 


    public ProductInfo(String name, String des, int ID, int num){
      this.name = name;
      this.des =des;
      this.ID = ID;
      this.num = num;
    }
}


        /**
     *
     */
    public static void Inventory(){

        }


    //creat Array
        ArrayList <ProductInfo> Inventory = new ArrayList <ProductInfo> ();

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        NameIn = new javax.swing.JTextField();
        IDIn = new javax.swing.JTextField();
        DesIn = new javax.swing.JTextField();
        NumIn = new javax.swing.JTextField();
        NameSearch = new javax.swing.JTextField();
        IDSearch = new javax.swing.JTextField();
        NameOut = new javax.swing.JLabel();
        IDOut = new javax.swing.JLabel();
        DesOut = new javax.swing.JLabel();
        NumOut = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        AddGo = new javax.swing.JButton();
        NameGo = new javax.swing.JButton();
        IDGo = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("jLabel1");

        jLabel2.setText("Name:");

        jLabel3.setText("ID");

        jLabel4.setText("Descripion");

        jLabel5.setText("Number");

        jLabel6.setText("Name");

        jLabel7.setText("ID");

        NameIn.setText("jTextField1");

        IDIn.setText("jTextField2");
        IDIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                IDInActionPerformed(evt);
            }
        });

        DesIn.setText("jTextField3");

        NumIn.setText("jTextField4");

        NameSearch.setText("jTextField5");

        IDSearch.setText("jTextField6");

        NameOut.setText("jLabel10");

        IDOut.setText("jLabel11");

        DesOut.setText("jLabel12");

        NumOut.setText("jLabel13");

        jLabel14.setText("Add");

        jLabel15.setText("Search by Name");

        jLabel16.setText("Search by ID");

        AddGo.setText("jButton1");
        AddGo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddGoActionPerformed(evt);
            }
        });

        NameGo.setText("jButton2");
        NameGo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NameGoActionPerformed(evt);
            }
        });

        IDGo.setText("jButton3");
        IDGo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                IDGoActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(0, 0, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(AddGo)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jLabel14)
                            .add(233, 233, 233))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jLabel15)
                            .add(222, 222, 222))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jLabel16)
                            .add(230, 230, 230)))))
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(225, 225, 225)
                                .add(jLabel1))
                            .add(layout.createSequentialGroup()
                                .add(99, 99, 99)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel7)
                                    .add(jLabel6)))
                            .add(layout.createSequentialGroup()
                                .add(126, 126, 126)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(IDGo)
                                    .add(layout.createSequentialGroup()
                                        .add(NameOut)
                                        .add(18, 18, 18)
                                        .add(IDOut)
                                        .add(18, 18, 18)
                                        .add(DesOut)))
                                .add(18, 18, 18)
                                .add(NumOut)))
                        .add(layout.createSequentialGroup()
                            .addContainerGap()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel2)
                                    .add(layout.createSequentialGroup()
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(jLabel4)
                                            .add(jLabel5)
                                            .add(jLabel3))
                                        .add(18, 18, 18)
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(NameSearch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 207, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                                .add(DesIn)
                                                .add(NumIn)
                                                .add(NameIn)
                                                .add(IDIn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 202, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
                                .add(IDSearch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 207, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .add(layout.createSequentialGroup()
                        .add(220, 220, 220)
                        .add(NameGo)))
                .addContainerGap(144, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 31, Short.MAX_VALUE)
                .add(jLabel14)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(NameIn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(IDIn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(DesIn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(NumIn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel5))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(AddGo)
                .add(18, 18, 18)
                .add(jLabel15)
                .add(24, 24, 24)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(NameSearch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel6))
                .add(18, 18, 18)
                .add(NameGo)
                .add(14, 14, 14)
                .add(jLabel16)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(IDSearch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel7))
                .add(18, 18, 18)
                .add(IDGo)
                .add(32, 32, 32)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(NameOut)
                    .add(IDOut)
                    .add(DesOut)
                    .add(NumOut))
                .add(64, 64, 64))
        );

        pack();
    }// </editor-fold>                        

    private void IDInActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
    }                                    

    private void IDGoActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // Search by ID

    }                                    

    private void AddGoActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // Add Item
        String Name, Description;
        int Identification, Number;

        Name = NameIn.getText();
        Description = DesIn.getText();
        Identification = Integer.parseInt(IDIn.getText());
        Number = Integer.parseInt(NumIn.getText());

        Inventory.add(new ProductInfo(Name, Description, Identification, Number));

        NameIn.setText("");
        DesIn.setText("");
        IDIn.setText("");
        NumIn.setText("");


    }                                     

    private void NameGoActionPerformed(java.awt.event.ActionEvent evt) {                                       
                // Search by Name
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(mVentory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(mVentory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(mVentory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(mVentory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new mVentory().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton AddGo;
    private javax.swing.JTextField DesIn;
    private javax.swing.JLabel DesOut;
    private javax.swing.JButton IDGo;
    private javax.swing.JTextField IDIn;
    private javax.swing.JLabel IDOut;
    private javax.swing.JTextField IDSearch;
    private javax.swing.JButton NameGo;
    private javax.swing.JTextField NameIn;
    private javax.swing.JLabel NameOut;
    private javax.swing.JTextField NameSearch;
    private javax.swing.JTextField NumIn;
    private javax.swing.JLabel NumOut;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

假设ProductInfo具有以下结构:

public class ProductInfo {

    private int id;
    private String name;
    private Foo someOtherField;

    public int getId () {
        return id;
    }

    public String getName () {
        return name;
    }

    //...

}

然后,您可以使用以下代码搜索ArrayList<ProductInfo>

public class Inventory {

    private ArrayList<ProductInfo> pis = new ArrayList<productInfo>();

    public ProductInfo find (int id, String name) {
        for(ProductInfo pi : pis) {
            if(pi.getId() == id && Objects.Equals(pi.getName(),name)) {
                return pi;
            }
        }
    }

}

这个方法应该由Inventory保护,因为控制器模式明确指出你应该将用户界面与数据操作分开。


您可以使用以下方式从JTextField实例中获取数据:

String name = NameIn.getText();
int id = Integer.Parse(IDIn.getText());

最后,当用户触发事件时,您需要某种处理方法来完成工作:

public class ButtonHandler implements ActionListener {

    private Inventory inventory;
    private JTextField idIn;
    private JTextField nameIn;

    public ButtonHandler(Inventory inventory, JTextField idIn, JTextField nameIn) {
        this.inventory = inventory;
        this.idIn = idIn;
        this.nameIn = nameIn;
    }

    public void actionPerformed(ActionEvent e) {
        String name = NameIn.getText();
        int id = Integer.Parse(IDIn.getText());
        ProductInfo pi = inventory.find(name,id);
        //do something with pi
    }
}

您需要创建此类处理程序,并添加侦听器:

ButtonHandler handler = new ButtonHandler(inventory,this.IDIn,this.NameIn);
someButton.addActionListener(this);

最后Java中的一些编码指南:

  • 字段的名称始终以小写字母开头。
  • 如前所述,使用不同的类,单独的职责,明确地将用户界面与数据操作分开。