我将如何从一个阵列到一个ArrayList切换? [英] How would I switch from an Array to an ArrayList?

查看:80
本文介绍了我将如何从一个阵列到一个ArrayList切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所有的数据保存到一个数组现在。如何将其切换到对象,而不是一个ArrayList的节约?我有一个基本的学生对象类书面但需要帮助过它的开关在一个ArrayList储蓄。所有帮助是极大的AP preciated。该ArrayList是第28行创建和数据设置在线路300的问题是如何修改code在一个ArrayList来存储,而不是

 公共类IAdvise扩展的JFrame {   日期格式DATEFORMAT =新的SimpleDateFormat(MM / DD / YYYY HH:MM:SS);
   的String [] COLUMNNAMES = {ID,姓名,大,政府采购协定,校园,家庭住址,电话号码,电子邮件,当前CST课程,过去的CST课程,Fusture CST课程,注释};
   对象[] []数据=新对象[60] [12];
   ArrayList的<的Student GT;人=新的ArrayList<的Student GT;();   JTable的表=新的JTable(数据为columnNames){
        @覆盖
      公共布尔的isCellEditable(INT行,诠释列){
         返回false;
      }
   };
   JFrame的帧,帧1;
   JPanel的buttonPanel,buttonPanel2,tablePanel,addPanel,editPanel;
   JLabel的labelID,标签,labelMajor,labelGPA,labelCampus,labelAddress,labelPhone,labelEmail,labelCurrent,labelPast,labelFuture,labelNotes;
   JTextField的txtID,txtName的,txtMajor,txtGPA,txtCampus,txtAddress,txtPhone,txtEmail,txtCurrent,txtPast,txtFuture,txtNotes;
   JButton的btnAdd,btnEdit,btnDelete,btnSort,btnSave,btnAddInput,btnCancel;
   INT键code和rowIndex,ROWNUMBER,noOfStudents;
   IAdvise.ButtonHandler BH =新IAdvise.ButtonHandler();
   公共IAdvise(){
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      。table.getSelectionModel()addListSelectionListener(新IAdvise.RowListener());
      table.getColumnModel()getColumn(1).SET preferredWidth(150)。
      table.getColumnModel()getColumn(2).SET preferredWidth(150)。
      table.getColumnModel()getColumn(3).SET preferredWidth(50)。
      table.getColumnModel()getColumn(4).SET preferredWidth(200)。
      table.getColumnModel()getColumn(5).SET preferredWidth(250)。
      table.getColumnModel()getColumn(6).SET preferredWidth(150)。
      table.getColumnModel()getColumn(7).SET preferredWidth(150)。
      table.getColumnModel()getColumn(8).SET preferredWidth(150)。
      table.getColumnModel()getColumn(9).SET preferredWidth(150)。
      table.getColumnModel()getColumn(10).SET preferredWidth(150)。
      table.getColumnModel()getColumn(11).SET preferredWidth(150)。      。table.getTableHeader()setResizingAllowed(假);
      。table.getTableHeader()setReorderingAllowed(假);
      JScrollPane的滚动窗格=新JScrollPane的(表);      btnAdd =的新的JButton(添加学生);
      btnAdd.addActionListener(BH);
      btnEdit =的新的JButton(编辑);
      btnEdit.addActionListener(BH);
      btnEdit.setEnabled(假);
      btnDelete =的新的JButton(删除);
      btnDelete.addActionListener(BH);
      btnDelete.setEnabled(假);
      btnSort =的新的JButton(更新);
      btnSort.addActionListener(BH);
      btnSave =的新的JButton(SAVE);
      btnSave.addActionListener(BH);
      btnSave.setActionCommand(保存);
      btnAddInput =的新的JButton(添加学生);
      btnAddInput.addActionListener(BH);
      btnAddInput.setActionCommand(AddInput);
      btnCancel =的新的JButton(取消);
      btnCancel.addActionListener(BH);      labelID =新的JLabel(ID);
      标签=新的JLabel(NAME);
      labelMajor =新的JLabel(主);
      labelGPA =新的JLabel(GPA);
      labelCampus =新的JLabel(校园);
      labelAddress =新的JLabel(地址);
      labelPhone =新的JLabel(电话号码);
      labelEmail =新的JLabel(电子邮件);
      labelCurrent =新的JLabel(当前CST课程);
      labelPast =新的JLabel(过去CST课程);
      labelFuture =新的JLabel(未来CST课程);
      labelNotes =新的JLabel(「票据」);
      txtID =新的JTextField(20);
      txtName的=新的JTextField(20);
      txtMajor =新的JTextField(20);
      txtGPA =新的JTextField(20);
      txtCampus =新的JTextField(20);
      txtAddress =新的JTextField(20);
      txtPhone =新的JTextField(20);
      txtEmail =新的JTextField(20);
      txtCurrent =新的JTextField(20);
      txtPast =新的JTextField(20);
      txtFuture =新的JTextField(20);
      txtNotes =新的JTextField(20);
      txtID.setDocument(新IAdvise.JTextFieldLimit(8));      txtID.addKeyListener(KeyListener的);      tablePanel =新JPanel();
      tablePanel.setLayout(新的BoxLayout(tablePanel,BoxLayout.PAGE_AXIS));
      tablePanel.setBorder(BorderFactory.createEmptyBorder(10,2,0,10));
      tablePanel.add(table.getTableHeader());
      tablePanel.add(表);
      JScrollPane的JScrollPane的=新JScrollPane的(tablePanel);
      scrollPane.setHorizo​​ntalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_​​AS_NEEDED);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_​​NEVER);
      scrollPane.setBounds(50,30,300,50);
      的JPanel的contentPane =新JPanel(NULL);
      contentPane.set preferredSize(新尺寸(500,400));
      contentPane.add(滚动窗格);      buttonPanel =新JPanel();
      buttonPanel.setLayout(新的GridBagLayout());
      GridBagConstraints的C =新的GridBagConstraints();      c.gridx = 0;
      c.gridy = 0;
      c.ipady = 20;
      c.insets =新插图(10,10,10,10);
      c.fill = GridBagConstraints.HORIZONTAL;
      buttonPanel.add(btnAdd,C);
      c.gridx = 0;
      c.gridy = 1;
      c.fill = GridBagConstraints.HORIZONTAL;
      c.ipady = 20;
      c.insets =新插图(10,10,10,10);
      buttonPanel.add(btnEdit,C);
      c.gridx = 0;
      c.gridy = 2;
      c.fill = GridBagConstraints.HORIZONTAL;
      c.ipady = 20;
      c.insets =新插图(10,10,10,10);
      buttonPanel.add(btnDelete,C);
      c.gridx = 0;
      c.gridy = 3;
      c.ipady = 20;
      c.insets =新插图(10,10,10,10);
      c.fill = GridBagConstraints.HORIZONTAL;
      buttonPanel.add(btnSort,C);
      c.gridx = 0;
      c.gridy = 4;
      c.ipady = 20;
      c.insets =新插图(10,10,10,10);
      c.fill = GridBagConstraints.HORIZONTAL;
      buttonPanel.add(btnSave,C);      帧=新的JFrame(家教数据库);
      frame.setVisible(真);
      frame.setResizable(假);
      frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
      frame.add(tablePanel,BorderLayout.CENTER);
      frame.add(buttonPanel,BorderLayout.EAST);
      frame.pack();      addPanel =新JPanel();
      addPanel.setLayout(新的GridBagLayout());      c.insets =新插图(1,0,1,1);
      c.gridx = 0;
      c.gridy = 0;
      addPanel.add(labelID,C);
      c.gridy = 1;
      addPanel.add(标签,C);
      c.gridy = 2;
      addPanel.add(labelMajor,C);
      c.gridy = 3;
      addPanel.add(labelGPA,C);
      c.gridy = 4;
      addPanel.add(labelCampus,C);
      c.gridy = 5;
      addPanel.add(labelAddress,C);
      c.gridy = 6;
      addPanel.add(labelPhone,C);
      c.gridy = 7;
      addPanel.add(labelEmail,C);
      c.gridy = 8;
      addPanel.add(labelCurrent,C);
      c.gridy = 9;
      addPanel.add(labelPast,C);
      c.gridy = 10;
      addPanel.add(labelFuture,C);
      c.gridy = 11;
      addPanel.add(labelNotes,C);
      //文本字段
      c.gridx = 1;
      c.gridy = 0;
      c.ipady = 1;
      addPanel.add(txtID,C);
      c.gridy = 1;
      c.ipady = 1;
      addPanel.add(txtName的,C);
      c.gridy = 2;
      c.ipady = 1;
      addPanel.add(txtMajor,C);
      c.gridy = 3;
      c.ipady = 1;
      addPanel.add(txtGPA,C);
      c.gridy = 4;
      c.ipady = 1;
      addPanel.add(txtCampus,C);
      c.gridy = 5;
      c.ipady = 1;
      addPanel.add(txtAddress,C);
      c.gridy = 6;
      c.ipady = 1;
      addPanel.add(txtPhone,C);
      c.gridy = 7;
      c.ipady = 1;
      addPanel.add(txtEmail,C);
      c.gridy = 8;
      c.ipady = 1;
      addPanel.add(txtCurrent,C);
      c.gridy = 9;
      c.ipady = 1;
      addPanel.add(txtPast,C);
      c.gridy = 10;
      c.ipady = 1;
      addPanel.add(txtFuture,C);
      c.gridy = 11;
      c.ipady = 1;
      addPanel.add(txtNotes,C);      buttonPanel2 =新JPanel();
      buttonPanel2.setLayout(新的GridLayout(1,1));
      buttonPanel2.add(btnAddInput);
      buttonPanel2.add(btnCancel);      帧1 =新的JFrame(学生数据库);
      frame1.setVisible(假);
      frame1.setResizable(假);
      frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
      frame1.add(addPanel,BorderLayout.CENTER);
      frame1.add(buttonPanel2,BorderLayout.PAGE_END);
      frame1.pack();
   }// 结束   的KeyListener的KeyListener =新的KeyListener(){
        @覆盖
      公共无效的keyTyped(KeyEvent的E){
      }        @覆盖
      公共无效键pressed(KeyEvent的E){
         关键code = e.getKey code();         如果((键code>!= 48安培;&放大器;关键code< = 57)及和放大器;!(关键code基= 96安培;&放大器;关键code< = 105)
                  &功放;&安培; !(关键code基= 37安培;&放大器;关键code< = 40)及和放大器; !(关键code == || 127键code == 8)){
            txtID.setEditable(假);
         }
      }        @覆盖
      公共无效调用keyReleased(KeyEvent的E){
         txtID.setEditable(真);
      }
   };   类RowListener实现ListSelectionListener {
        @覆盖
      公共无效的valueChanged(ListSelectionEvent事件){
         如果(event.getValueIsAdjusting()){
            rowIndex位置= table.getSelectedRow();
            如果(数据[rowIndex位置] [0] == NULL ||数据[rowIndex位置] [0] ==){
               btnEdit.setEnabled(假);
               btnDelete.setEnabled(假);
            }其他{
               btnEdit.setEnabled(真);
               btnDelete.setEnabled(真);
            }
         }
      }
   }   类ButtonHandler实现的ActionListener {
      公共无效的actionPerformed(ActionEvent的五){               如果(e.getActionCommand()。等于(添加学生)){
               txtID.setText();
               txtName.setText();
               txtMajor.setText();
               txtGPA.setText();
               txtCampus.setText();
               txtAddress.setText();
               txtPhone.setText();
               txtEmail.setText();
               txtCurrent.setText();
               txtPast.setText();
               txtFuture.setText();
               txtNotes.setText();
                学生学生=新的学生(txtID.getText(),txtName.getName(),txtMajor.getText(),txtGPA.getText(),txtCampus.getText(),txtAddress.getText(),txtPhone.getText(),txtEmail。的getText(),txtCurrent.getText(),txtPast.getText(),txtFuture.getText(),txtNotes.getText());
                al.add(学生);               frame1.setTitle(添加学生数据); //用于添加标题栏名称
               frame1.setVisible(真);               }否则如果(e.getActionCommand()。等于(编辑)){
               txtID.setText(数据[rowIndex位置] [0] +);
               txtName.setText(数据[rowIndex位置] [1] +);
               txtMajor.setText(数据[rowIndex位置] [2] +);
               txtGPA.setText(数据[rowIndex位置] [3] +);
               txtCampus.setText(数据[rowIndex位置] [4] +);
               txtAddress.setText(数据[rowIndex位置] [5] +);
               txtPhone.setText(数据[rowIndex位置] [6] +);
               txtEmail.setText(数据[rowIndex位置] [7] +);
               txtCurrent.setText(数据[rowIndex位置] [8] +);
               txtPast.setText(数据[rowIndex位置] [9] +);
               txtFuture.setText(数据[rowIndex位置] [10] +);
               txtNotes.setText(数据[rowIndex位置] [11] +);
               txtID.setEditable(假);
               frame1.setTitle(输入学生数据);
               btnAddInput.setActionCommand(EDIT2);
               btnAddInput.setText(接受);               frame1.setVisible(真);
            }否则如果(e.getActionCommand()。等于(删除)){
               INT确认= JOptionPane.showConfirmDialog(帧,你确定?,确认,
                        JOptionPane.YES_NO_OPTION);               如果(确认== 0){
                  rowIndex位置= table.getSelectedRow();
                  ROWNUMBER = 0;                  noOfStudents--;
                  的for(int i = 0; I< = 10;我++){
                     如果(rowIndex位置= I和!&放大器; I&下; = noOfStudents){
                        数据[ROWNUMBER] [0] =数据[I] [0];
                        数据[ROWNUMBER] [1] =数据[I] [1];
                        数据[ROWNUMBER] [2] =数据[I] [2];
                        数据[ROWNUMBER] [3] =数据[I] [3];
                        数据[ROWNUMBER] [4] =数据[I] [4];
                        数据[ROWNUMBER] [5] =数据[I] [5];
                        数据[ROWNUMBER] [6] =数据[I] [6];
                        数据[ROWNUMBER] [7] =数据[I] [7];
                        数据[ROWNUMBER] [8] =数据[I] [8];
                        数据[ROWNUMBER] [9] =数据[I] [9];
                        数据[ROWNUMBER] [10] =数据[I] [10];
                        数据[ROWNUMBER] [11] =数据[I] [11];
                        ROWNUMBER ++;
                     }否则如果(rowIndex位置= I和!&放大器; I> noOfStudents){
                        数据[ROWNUMBER] [0] =;
                        数据[ROWNUMBER] [1] =;
                        数据[ROWNUMBER] [2] =;
                        数据[ROWNUMBER] [3] =;
                        数据[ROWNUMBER] [4] =;
                        数据[ROWNUMBER] [5] =;
                        数据[ROWNUMBER] [6] =;
                        数据[ROWNUMBER] [7] =;
                        数据[ROWNUMBER] [8] =;
                        数据[ROWNUMBER] [9] =;
                        数据[ROWNUMBER] [10] =;
                        数据[ROWNUMBER] [11] =;                        ROWNUMBER ++;
                     }
                  }
                  如果(noOfStudents == 1000){
                       btnAdd.setEnabled(假);
                   }
                  其他{
                       btnAdd.setEnabled(真);
                   }
                  如果(noOfStudents == 0){
                     btnDelete.setEnabled(假);
                     btnEdit.setEnabled(假);
                  }其他{
                     btnDelete.setEnabled(真);
                     btnEdit.setEnabled(真);
                  }                  rowIndex位置= table.getSelectedRow();
                  如果(数据[rowIndex位置] [0] == NULL ||数据[rowIndex位置] [0] ==){
                     btnEdit.setEnabled(假);
                     btnDelete.setEnabled(假);
                  }其他{
                     btnEdit.setEnabled(真);
                     btnDelete.setEnabled(真);
                  }                  table.updateUI();               }
            }否则如果(e.getActionCommand()。等于(AddInput)){               如果(txtID.getText()的isEmpty()|| txtName.getText()的isEmpty()
                        || txtMajor.getText()的isEmpty()// /
                        || txtGPA.getText()的isEmpty()|| txtCampus.getText()的isEmpty()|| txtEmail.getText()的isEmpty()
                       || txtCurrent.getText()的isEmpty()|| txtPast.getText()的isEmpty()|| txtFuture.getText()的isEmpty()
                       || txtNotes.getText()的isEmpty()|| txtPhone.getText()。的isEmpty()){
                  JOptionPane.showMessageDialog(NULL,请填写空白IN,错误!,
                  JOptionPane.ERROR_MESSAGE);
               }
                其他{
                  INT DUP = 0;
                  的for(int i = 0; I< 8;我++){
                     如果(txtID.getText()。等于(数据[I] [0])){
                        JOptionPane.showMessageDialog(NULL,身份证号已经存在。,错误!,
                                 JOptionPane.ERROR_MESSAGE);
                        DUP ++;
                     }
                  }
                  如果(DUP == 0){
                     rowIndex位置= table.getSelectedRow();
                     数据[noOfStudents] [0] = txtID.getText();
                     数据[noOfStudents] [1] = txtName.getText();
                     数据[noOfStudents] [2] = txtMajor.getText();
                     数据[noOfStudents] [3] = txtGPA.getText();
                     数据[noOfStudents] [4] = txtCampus.getText();
                     数据[noOfStudents] [5] = txtAddress.getText();
                     数据[noOfStudents] [6] = txtPhone.getText();
                     数据[noOfStudents] [7] = txtEmail.getText();
                     数据[noOfStudents] [8] = txtCurrent.getText();
                     数据[noOfStudents] [9] = txtPast.getText();
                     数据[noOfStudents] [10] = txtFuture.getText();
                     数据[noOfStudents] [11] = txtNotes.getText();                     table.updateUI();
                     frame1.dispose();
                     noOfStudents ++;
                     如果(noOfStudents == 50){
                        btnAdd.setEnabled(假);
                     }
                        其他{
                          btnAdd.setEnabled(真);
                      }
                     如果(数据[rowIndex位置] [0] == NULL){
                        btnEdit.setEnabled(假);
                        btnDelete.setEnabled(假);
                     }其他{
                        btnEdit.setEnabled(真);
                        btnDelete.setEnabled(真);
                     }
                  }
               }
               table.updateUI();
            }否则如果(e.getActionCommand()。等于(保存)){
                尝试{
            为PrintWriter了=的新PrintWriter(Tutor.txt);
            的for(int i = 0;我α25,我++)
   {
      为(中间体J = 0; J&小于10; J ++)
      {
          的out.print(数据[I] [J]);
          的out.print(,);
      如果(J == 10){
         通过out.println();
      }
      }了out.flush();        }}赶上(FileNotFoundException异常前){
        }
              }否则如果(e.getActionCommand()。等于(更新)){            }
               如果(txtID.getText()的isEmpty()|| txtName.getText()的isEmpty()
                        || txtMajor.getText()的isEmpty()// /
                        || txtGPA.getText()的isEmpty()|| txtCampus.getText()的isEmpty()|| txtEmail.getText()的isEmpty()
                       || txtCurrent.getText()的isEmpty()|| txtPast.getText()的isEmpty()|| txtFuture.getText()的isEmpty()
                       || txtNotes.getText()。的isEmpty()){
               }其他{
                  数据[rowIndex位置] [0] = txtID.getText();
                  数据[rowIndex位置] [1] = txtName.getText();
                  数据[rowIndex位置] [2] = txtMajor.getText();
                  数据[rowIndex位置] [3] = txtGPA.getText();
                  数据[rowIndex位置] [4] = txtCampus.getText();
                  数据[rowIndex位置] [5] = txtAddress.getText();
                  数据[rowIndex位置] [6] = txtPhone.getText();
                  数据[rowIndex位置] [7] = txtEmail.getText();
                  数据[rowIndex位置] [8] = txtEmail.getText();
                  数据[rowIndex位置] [9] = txtEmail.getText();
                  数据[rowIndex位置] [10] = txtEmail.getText();
                  数据[rowIndex位置] [11] = txtEmail.getText();
                frame1.dispose();
               }
               table.updateUI();      }
   }   类JTextFieldLimit扩展PlainDocument {
      私人诠释限制;      JTextFieldLimit(INT限制){
         超();
         this.limit =限制;
      }      JTextFieldLimit(INT限制,布尔上部){
         超();
         this.limit =限制;
      }        @覆盖
      公共无效insertString(INT抵消,字符串str的AttributeSet attr)使用
               抛出BadLocationException的{
         如果(STR == NULL){
                       返回;
                   }         如果((的getLength()+ str.length())≤=极限){
            super.insertString(偏移,STR,attr)使用;
         }
      }
   }
   公共静态无效的主要(字串[] args){
      新IAdvise();
   }
}

学生班级:

 公共类学生实现java.io.Serialize {
    私人最终字符串ID;
    私人最终字符串名称;
    私人最终字符串专业;
    私人最终字符串GPA;
    私人最终字符串校园;
    私人最终字符串地址;
    私人最终串号;
    私人最终字符串电子邮件;
    私人最终字符串电流;
    私人最终字符串过去;
    私人最终字符串的未来;
   公益助学(ID字符串,字符串名称,弦乐专业,GPA的字符串,字符串校区,地址字符串,字符串数字,字符串电子邮件,当前字符串,字符串过去,未来的字符串,字符串注释){
        this.id = ID;
        this.name =名称;
        this.major =专业;
        this.gpa = GPA;
        this.campus =校园;
        this.address =地址;
        this.number =号;
        this.email =电子邮件;
        this.current =电流;
        this.past =过去;
        this.future =未来;
   }
}


解决方案

要更改使用数组为code使用code的的ArrayList


  1. 而不是 A [I] ,当它不是在赋值的左侧,使用 a.get(I)


  2. 而不是则为a.length 中,使用 a.size()


  3. 而不是设置的[I] =前pression :如果 I 是已知在范围内(0℃= I < = 则为a.length-1 ),使用 a.set(I,前pression)。如果我==则为a.length ,你不能使用 A [i] =前pression a.add(如pression)的ArrayList ,1增加的大小做C $ C>。如果 I>则为a.length ,所以要在 ArrayList中添加新元素留下缺口,则是这样的:

     而(a.size()< I)
        a.add(NULL);
    //在这一点上a.size ==我
    a.add(如pression);
    //现在a.size == I + 1


这应包括对数组所有的基本操作。有没有相应的操作在的ArrayList ,如阵列定义了一些实用操作>的binarySearch 。

I have all the data saving to an array right now. How would I switch it to saving in a ArrayList of objects instead? I have a basic student object class written but need help switching it over to saving in an Arraylist. All help is greatly appreciated. The arraylist is created on line 28 and the data is set at line 300. The question is how to modify code to store in an ArrayList instead

public class IAdvise extends JFrame {

   DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
   String[] columnNames = {"ID", "Name", "Major", "GPA", "Campus", "Home Address", "Phone Number", "Email", "Current CST courses", "Past CST course", "Fusture CST courses", "Notes"};
   Object[][] data = new Object[60][12];
   ArrayList<Student> al = new ArrayList<Student>();

   JTable table = new JTable(data, columnNames) {
        @Override
      public boolean isCellEditable(int row, int column) {
         return false;
      }
   };
   JFrame frame, frame1;
   JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
   JLabel labelID, labelName, labelMajor, labelGPA, labelCampus, labelAddress, labelPhone, labelEmail,labelCurrent, labelPast, labelFuture, labelNotes;
   JTextField txtID, txtName, txtMajor, txtGPA, txtCampus, txtAddress, txtPhone, txtEmail, txtCurrent, txtPast, txtFuture, txtNotes;
   JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
   int keyCode, rowIndex, rowNumber, noOfStudents;
   IAdvise.ButtonHandler bh = new IAdvise.ButtonHandler();


   public IAdvise() {
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      table.getSelectionModel().addListSelectionListener(new IAdvise.RowListener());
      table.getColumnModel().getColumn(1).setPreferredWidth(150);
      table.getColumnModel().getColumn(2).setPreferredWidth(150);
      table.getColumnModel().getColumn(3).setPreferredWidth(50);
      table.getColumnModel().getColumn(4).setPreferredWidth(200);
      table.getColumnModel().getColumn(5).setPreferredWidth(250);
      table.getColumnModel().getColumn(6).setPreferredWidth(150);
      table.getColumnModel().getColumn(7).setPreferredWidth(150);
      table.getColumnModel().getColumn(8).setPreferredWidth(150);
      table.getColumnModel().getColumn(9).setPreferredWidth(150);
      table.getColumnModel().getColumn(10).setPreferredWidth(150);
      table.getColumnModel().getColumn(11).setPreferredWidth(150);

      table.getTableHeader().setResizingAllowed(false);
      table.getTableHeader().setReorderingAllowed(false);
      JScrollPane scrollPane = new JScrollPane(table);

      btnAdd = new JButton("Add Student");
      btnAdd.addActionListener(bh);
      btnEdit = new JButton("EDIT");
      btnEdit.addActionListener(bh);
      btnEdit.setEnabled(false); 
      btnDelete = new JButton("DELETE");
      btnDelete.addActionListener(bh);
      btnDelete.setEnabled(false);
      btnSort = new JButton("Update");
      btnSort.addActionListener(bh);
      btnSave = new JButton("SAVE");
      btnSave.addActionListener(bh);
      btnSave.setActionCommand("Save");


      btnAddInput = new JButton("Add Student");
      btnAddInput.addActionListener(bh);
      btnAddInput.setActionCommand("AddInput");
      btnCancel = new JButton("Cancel");
      btnCancel.addActionListener(bh);

      labelID = new JLabel("ID");
      labelName = new JLabel("NAME");
      labelMajor = new JLabel("Major");
      labelGPA = new JLabel("GPA");
      labelCampus = new JLabel("Campus");
      labelAddress = new JLabel("Address");
      labelPhone = new JLabel("Phone Number");
      labelEmail = new JLabel("Email");
      labelCurrent = new JLabel("Current CST courses");
      labelPast = new JLabel("Past CST courses");
      labelFuture = new JLabel("Future CST courses");
      labelNotes = new JLabel("Notes");
      txtID = new JTextField(20);
      txtName = new JTextField(20);
      txtMajor = new JTextField(20);
      txtGPA = new JTextField(20);
      txtCampus = new JTextField(20);
      txtAddress = new JTextField(20);
      txtPhone = new JTextField(20);
      txtEmail = new JTextField(20);
      txtCurrent = new JTextField(20);
      txtPast = new JTextField(20);
      txtFuture = new JTextField(20);
      txtNotes = new JTextField(20);


      txtID.setDocument(new IAdvise.JTextFieldLimit(8)); 

      txtID.addKeyListener(keyListener); 

      tablePanel = new JPanel();
      tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
      tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
      tablePanel.add(table.getTableHeader());
      tablePanel.add(table);
      JScrollPane jScrollPane = new JScrollPane(tablePanel);
      scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
      scrollPane.setBounds(50, 30, 300, 50);
      JPanel contentPane = new JPanel(null);
      contentPane.setPreferredSize(new Dimension(500, 400));
      contentPane.add(scrollPane);

      buttonPanel = new JPanel();
      buttonPanel.setLayout(new GridBagLayout());
      GridBagConstraints c = new GridBagConstraints();

      c.gridx = 0;
      c.gridy = 0;
      c.ipady = 20;
      c.insets = new Insets(10, 10, 10, 10);
      c.fill = GridBagConstraints.HORIZONTAL;
      buttonPanel.add(btnAdd, c);
      c.gridx = 0;
      c.gridy = 1;
      c.fill = GridBagConstraints.HORIZONTAL;
      c.ipady = 20;
      c.insets = new Insets(10, 10, 10, 10);
      buttonPanel.add(btnEdit, c);
      c.gridx = 0;
      c.gridy = 2;
      c.fill = GridBagConstraints.HORIZONTAL;
      c.ipady = 20;
      c.insets = new Insets(10, 10, 10, 10);
      buttonPanel.add(btnDelete, c);
      c.gridx = 0;
      c.gridy = 3;
      c.ipady = 20;
      c.insets = new Insets(10, 10, 10, 10);
      c.fill = GridBagConstraints.HORIZONTAL;
      buttonPanel.add(btnSort, c);
      c.gridx = 0;
      c.gridy = 4;
      c.ipady = 20;
      c.insets = new Insets(10, 10, 10, 10);
      c.fill = GridBagConstraints.HORIZONTAL;
      buttonPanel.add(btnSave, c);

      frame = new JFrame("Tutoring Database");
      frame.setVisible(true);
      frame.setResizable(false);
      frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
      frame.add(tablePanel, BorderLayout.CENTER);
      frame.add(buttonPanel, BorderLayout.EAST);
      frame.pack();

      addPanel = new JPanel();
      addPanel.setLayout(new GridBagLayout());

      c.insets = new Insets(1, 0, 1, 1);
      c.gridx = 0;
      c.gridy = 0;
      addPanel.add(labelID, c);
      c.gridy = 1;
      addPanel.add(labelName, c);
      c.gridy = 2;
      addPanel.add(labelMajor, c);
      c.gridy = 3;
      addPanel.add(labelGPA, c);
      c.gridy = 4;
      addPanel.add(labelCampus, c);
      c.gridy = 5;
      addPanel.add(labelAddress, c);
      c.gridy = 6;
      addPanel.add(labelPhone, c);
      c.gridy = 7;
      addPanel.add(labelEmail, c);
      c.gridy = 8;
      addPanel.add(labelCurrent, c);
      c.gridy = 9;
      addPanel.add(labelPast, c);
      c.gridy = 10;
      addPanel.add(labelFuture, c);
      c.gridy = 11;
      addPanel.add(labelNotes, c);
      // text fields
      c.gridx = 1;
      c.gridy = 0;
      c.ipady = 1;
      addPanel.add(txtID, c);
      c.gridy = 1;
      c.ipady = 1;
      addPanel.add(txtName, c);
      c.gridy = 2;
      c.ipady = 1;
      addPanel.add(txtMajor, c);
      c.gridy = 3;
      c.ipady = 1;
      addPanel.add(txtGPA, c);
      c.gridy = 4;
      c.ipady = 1;
      addPanel.add(txtCampus, c);
      c.gridy = 5;
      c.ipady = 1;
      addPanel.add(txtAddress, c);
      c.gridy = 6;
      c.ipady = 1;
      addPanel.add(txtPhone, c);
      c.gridy = 7;
      c.ipady = 1;
      addPanel.add(txtEmail, c);
      c.gridy = 8;
      c.ipady = 1;
      addPanel.add(txtCurrent, c);
      c.gridy = 9;
      c.ipady = 1;
      addPanel.add(txtPast, c);
      c.gridy = 10;
      c.ipady = 1;
      addPanel.add(txtFuture, c);
      c.gridy = 11;
      c.ipady = 1;
      addPanel.add(txtNotes, c);

      buttonPanel2 = new JPanel();
      buttonPanel2.setLayout(new GridLayout(1, 1));
      buttonPanel2.add(btnAddInput);
      buttonPanel2.add(btnCancel);

      frame1 = new JFrame("Student Database");
      frame1.setVisible(false);
      frame1.setResizable(false);
      frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
      frame1.add(addPanel, BorderLayout.CENTER);
      frame1.add(buttonPanel2, BorderLayout.PAGE_END);
      frame1.pack();
   }// end

   KeyListener keyListener = new KeyListener() {
        @Override
      public void keyTyped(KeyEvent e) {
      }

        @Override
      public void keyPressed(KeyEvent e) {
         keyCode = e.getKeyCode();

         if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
                  && !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
            txtID.setEditable(false);
         }
      }

        @Override
      public void keyReleased(KeyEvent e) {
         txtID.setEditable(true);
      }
   };

   class RowListener implements ListSelectionListener {
        @Override
      public void valueChanged(ListSelectionEvent event) {
         if (event.getValueIsAdjusting()) {
            rowIndex = table.getSelectedRow();
            if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
               btnEdit.setEnabled(false);
               btnDelete.setEnabled(false);
            } else {
               btnEdit.setEnabled(true);
               btnDelete.setEnabled(true);
            }
         }
      }
   }

   class ButtonHandler implements ActionListener {
      public void actionPerformed(ActionEvent e) {

               if (e.getActionCommand().equals("Add Student")) {
               txtID.setText("");
               txtName.setText("");
               txtMajor.setText("");
               txtGPA.setText("");
               txtCampus.setText("");
               txtAddress.setText("");
               txtPhone.setText("");
               txtEmail.setText("");
               txtCurrent.setText("");
               txtPast.setText("");
               txtFuture.setText("");
               txtNotes.setText("");
                Student student = new Student(txtID.getText(), txtName.getName(), txtMajor.getText(), txtGPA.getText(), txtCampus.getText(), txtAddress.getText(), txtPhone.getText(),txtEmail.getText(), txtCurrent.getText(), txtPast.getText(), txtFuture.getText(), txtNotes.getText());
                al.add(student);

               frame1.setTitle("Add Student data"); // title bar name for add
               frame1.setVisible(true);

               } else if (e.getActionCommand().equals("EDIT")) {
               txtID.setText(data[rowIndex][0] + ""); 
               txtName.setText(data[rowIndex][1] + ""); 
               txtMajor.setText(data[rowIndex][2] + "");
               txtGPA.setText(data[rowIndex][3] + "");
               txtCampus.setText(data[rowIndex][4] + "");
               txtAddress.setText(data[rowIndex][5] + "");
               txtPhone.setText(data[rowIndex][6] + "");
               txtEmail.setText(data[rowIndex][7] + "");
               txtCurrent.setText(data[rowIndex][8] + "");
               txtPast.setText(data[rowIndex][9] + "");
               txtFuture.setText(data[rowIndex][10] + "");
               txtNotes.setText(data[rowIndex][11] + "");
               txtID.setEditable(false); 
               frame1.setTitle("Enter Student data"); 
               btnAddInput.setActionCommand("Edit2");
               btnAddInput.setText("ACCEPT");

               frame1.setVisible(true); 
            } else if (e.getActionCommand().equals("DELETE")) {
               int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
                        JOptionPane.YES_NO_OPTION);

               if (confirm == 0) {
                  rowIndex = table.getSelectedRow();
                  rowNumber = 0;

                  noOfStudents--;
                  for (int i = 0; i <= 10; i++) {
                     if (rowIndex != i && i <= noOfStudents) {
                        data[rowNumber][0] = data[i][0];
                        data[rowNumber][1] = data[i][1];
                        data[rowNumber][2] = data[i][2];
                        data[rowNumber][3] = data[i][3];
                        data[rowNumber][4] = data[i][4];
                        data[rowNumber][5] = data[i][5];
                        data[rowNumber][6] = data[i][6];
                        data[rowNumber][7] = data[i][7];
                        data[rowNumber][8] = data[i][8];
                        data[rowNumber][9] = data[i][9];
                        data[rowNumber][10] = data[i][10];
                        data[rowNumber][11] = data[i][11];


                        rowNumber++;
                     } else if (rowIndex != i && i > noOfStudents) {
                        data[rowNumber][0] = "";
                        data[rowNumber][1] = "";
                        data[rowNumber][2] = "";
                        data[rowNumber][3] = "";
                        data[rowNumber][4] = "";
                        data[rowNumber][5] = "";
                        data[rowNumber][6] = "";
                        data[rowNumber][7] = "";
                        data[rowNumber][8] = "";
                        data[rowNumber][9] = "";
                        data[rowNumber][10] = "";
                        data[rowNumber][11] = "";

                        rowNumber++;
                     }
                  }
                  if (noOfStudents == 1000) {
                       btnAdd.setEnabled(false);
                   }
                  else {
                       btnAdd.setEnabled(true);
                   }
                  if (noOfStudents == 0) {
                     btnDelete.setEnabled(false);
                     btnEdit.setEnabled(false);
                  } else {
                     btnDelete.setEnabled(true);
                     btnEdit.setEnabled(true);
                  }

                  rowIndex = table.getSelectedRow();
                  if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
                     btnEdit.setEnabled(false);
                     btnDelete.setEnabled(false);
                  } else {
                     btnEdit.setEnabled(true);
                     btnDelete.setEnabled(true);
                  }

                  table.updateUI();

               }
            } else if (e.getActionCommand().equals("AddInput")) {

               if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
                        || txtMajor.getText().isEmpty()// /
                        || txtGPA.getText().isEmpty() || txtCampus.getText().isEmpty()|| txtEmail.getText().isEmpty()
                       || txtCurrent.getText().isEmpty()|| txtPast.getText().isEmpty()|| txtFuture.getText().isEmpty()
                       || txtNotes.getText().isEmpty() || txtPhone.getText().isEmpty()) {
                  JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
                  JOptionPane.ERROR_MESSAGE);
               }
                else {
                  int dup = 0;
                  for (int i = 0; i < 8; i++) {
                     if (txtID.getText().equals(data[i][0])) {
                        JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
                                 JOptionPane.ERROR_MESSAGE);
                        dup++;
                     }
                  }
                  if (dup == 0) {
                     rowIndex = table.getSelectedRow();
                     data[noOfStudents][0] = txtID.getText();
                     data[noOfStudents][1] = txtName.getText();
                     data[noOfStudents][2] = txtMajor.getText();
                     data[noOfStudents][3] = txtGPA.getText();
                     data[noOfStudents][4] = txtCampus.getText();
                     data[noOfStudents][5] = txtAddress.getText();
                     data[noOfStudents][6] = txtPhone.getText();
                     data[noOfStudents][7] = txtEmail.getText();
                     data[noOfStudents][8] = txtCurrent.getText();
                     data[noOfStudents][9] = txtPast.getText();
                     data[noOfStudents][10] = txtFuture.getText();
                     data[noOfStudents][11] = txtNotes.getText();



                     table.updateUI();
                     frame1.dispose();
                     noOfStudents++;
                     if (noOfStudents == 50){
                        btnAdd.setEnabled(false);
                     }
                        else {
                          btnAdd.setEnabled(true);
                      }
                     if (data[rowIndex][0] == null) {
                        btnEdit.setEnabled(false);
                        btnDelete.setEnabled(false);
                     } else {
                        btnEdit.setEnabled(true);
                        btnDelete.setEnabled(true);
                     }
                  }
               }
               table.updateUI();
            }else if(e.getActionCommand().equals("Save")){
                try {
            PrintWriter out = new PrintWriter("Tutor.txt");
            for(int i = 0; i < 25; i++)
   {
      for(int j = 0; j < 10; j++)
      {
          out.print(data[i][j]);
          out.print(", ");
      if(j == 10){   
         out.println();
      }
      }     out.flush();

        }} catch (FileNotFoundException ex) {
        }
              } else if (e.getActionCommand().equals("Update")) {

            }
               if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
                        || txtMajor.getText().isEmpty()// /
                        || txtGPA.getText().isEmpty() || txtCampus.getText().isEmpty()|| txtEmail.getText().isEmpty()
                       || txtCurrent.getText().isEmpty()|| txtPast.getText().isEmpty()|| txtFuture.getText().isEmpty()
                       || txtNotes.getText().isEmpty()) {
               } else {
                  data[rowIndex][0] = txtID.getText();
                  data[rowIndex][1] = txtName.getText();
                  data[rowIndex][2] = txtMajor.getText();
                  data[rowIndex][3] = txtGPA.getText();
                  data[rowIndex][4] = txtCampus.getText();
                  data[rowIndex][5] = txtAddress.getText();
                  data[rowIndex][6] = txtPhone.getText();
                  data[rowIndex][7] = txtEmail.getText();
                  data[rowIndex][8] = txtEmail.getText();
                  data[rowIndex][9] = txtEmail.getText();
                  data[rowIndex][10] = txtEmail.getText();
                  data[rowIndex][11] = txtEmail.getText();


                frame1.dispose();
               }
               table.updateUI();

      }
   }

   class JTextFieldLimit extends PlainDocument {
      private int limit;

      JTextFieldLimit(int limit) {
         super();
         this.limit = limit;
      }

      JTextFieldLimit(int limit, boolean upper) {
         super();
         this.limit = limit;
      }

        @Override
      public void insertString(int offset, String str, AttributeSet attr)
               throws BadLocationException {
         if (str == null) {
                       return;
                   }

         if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
         }
      }
   }
   public static void main(String[] args) {
      new IAdvise();
   }
}

Student Class:

public class Student implements java.io.Serialize{
    private final String id;
    private final String name;
    private final String major;
    private final String gpa;
    private final String campus;
    private final String address;
    private final String number;
    private final String email;
    private final String current;
    private final String past;
    private final String future;


   public Student(String id, String name, String major,String gpa, String campus, String address,String number, String email, String current, String past, String future, String notes) {
        this.id = id;
        this.name = name;
        this.major = major;
        this.gpa = gpa;
        this.campus = campus;
        this.address = address;
        this.number = number;
        this.email = email;
        this.current = current;
        this.past = past;
        this.future = future;
   }
}

解决方案

To change code that uses an array into code that uses an ArrayList:

  1. Instead of a[i], when it's not on the left side of an assignment, use a.get(i)

  2. Instead of a.length, use a.size()

  3. Instead of setting a[i] = expression: if i is known to be in range (0 <= i <= a.length-1), use a.set(i, expression). If i == a.length, you couldn't use a[i] = expression with an array, but you can do it with an ArrayList, increasing the size by 1: a.add(expression). If i > a.length, so that you want to add a new element in the ArrayList leaving a gap, then something like:

    while (a.size() < i)
        a.add (null);
    // at this point a.size == i
    a.add (expression);
    // now a.size == i+1
    

That should cover all the basic operations on arrays. There are some utility operations defined in Arrays that don't have equivalent operations in ArrayList, like binarySearch.

这篇关于我将如何从一个阵列到一个ArrayList切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆