保存和检索数据

时间:2013-12-15 21:48:41

标签: java swing jframe jpanel jbutton

该程序需要能够存储所提供和可检索的信息。我想要发生的是当单击保存按钮时它将保存数据,当单击编辑按钮时,它将填充信息保存表。我试图添加一个滚动条。 “保存”按钮命令位于第379行,编辑按钮位于357 滚动条在第100行我知道我的代码很糟糕,但我是一个初学者,它是我迄今为止最好的。任何帮助表示赞赏。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class IAdvise extends JFrame {

   DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
   String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor", "Login Time", "Logout Time"};
   Object[][] data = new Object[30][7];

   // table
   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, labelCourse, labelProfessor, labelHelp, labelDate, labelDate2;
   JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp, txtDate, txtDate2;
   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(3).setPreferredWidth(100);
      table.getColumnModel().getColumn(4).setPreferredWidth(200);
      table.getColumnModel().getColumn(5).setPreferredWidth(150);
      table.getColumnModel().getColumn(6).setPreferredWidth(150);


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

      btnAdd = new JButton("Login");
      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("Logout");
      btnSort.addActionListener(bh);
      btnSave = new JButton("SAVE");
      btnSave.addActionListener(bh);
      btnSave.setActionCommand("Save");


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

      labelID = new JLabel("ID");
      labelName = new JLabel("NAME");
      labelCourse = new JLabel("Course");
      labelProfessor = new JLabel("Professor");
      labelHelp = new JLabel("Reason for Tutoring");
      labelDate = new JLabel("Login");
      labelDate2 = new JLabel("Logout");
      txtID = new JTextField(20);
      txtName = new JTextField(20);
      txtCourse = new JTextField(20);
      txtProfessor = new JTextField(20);
      txtHelp = new JTextField(20);
      txtDate = new JTextField(20);
      txtDate2 = new JTextField(20);
      txtID.setDocument(new IAdvise.JTextFieldLimit(15)); 

      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(labelCourse, c);
      c.gridy = 3;
      addPanel.add(labelProfessor, c);
      c.gridy = 4;
      addPanel.add(labelHelp, c);
      c.gridy = 5;
      addPanel.add(labelDate, c);
      c.gridy = 6;
      addPanel.add(labelDate2, 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(txtCourse, c);
      c.gridy = 3;
      c.ipady = 1;
      addPanel.add(txtProfessor, c);
      c.gridy = 4;
      c.ipady = 1;
      addPanel.add(txtHelp, c);
      c.gridy = 5;
      c.ipady = 1;
      addPanel.add(txtDate, c);
      c.gridy = 5;
      c.ipady = 1;
      addPanel.add(txtDate2, 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) {
                  Date date = new Date();

               if (e.getActionCommand().equals("Login")) {
               txtID.setText("");
               txtName.setText("");
               txtCourse.setText("");
               txtProfessor.setText("");
               txtHelp.setText("");
               txtDate.setText(dateFormat.format(date));


               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] + ""); 
               txtCourse.setText(data[rowIndex][2] + "");
               txtProfessor.setText(data[rowIndex][3] + "");
               txtHelp.setText(data[rowIndex][4] + "");
               txtDate.setText(data[rowIndex][5] + "");
               txtDate2.setText(data[rowIndex][6] + "");
               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];


                        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] = "";

                        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()
                        || txtCourse.getText().isEmpty()// /
                        || txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
                  JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
                  JOptionPane.ERROR_MESSAGE);
               }
                else {
                  int dup = 0;
                  for (int i = 0; i < 10; 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] = txtCourse.getText();
                     data[noOfStudents][3] = txtProfessor.getText();
                     data[noOfStudents][4] = txtHelp.getText();
                     data[noOfStudents][5] = txtDate.getText();
                     data[noOfStudents][6] = txtDate2.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 < 7; j++)
      {
          out.print(data[i][j]);
          out.print(", ");
      if(j == 6){   
         out.println();
      }
      }     out.flush();

        }} catch (FileNotFoundException ex) {
        }
              } else if (e.getActionCommand().equals("Logout")) {
               Date date2 = new Date();
                  int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
                JOptionPane.YES_NO_OPTION);
                if (confirm == 0) {
                  rowIndex = table.getSelectedRow();
                  rowNumber = 0;
                  txtDate2.setText(dateFormat.format(date2));
                }
            }
               if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
                        || txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
                        || txtHelp.getText().isEmpty()|| txtHelp.getText().isEmpty()) {
               } else {
                  data[rowIndex][0] = txtID.getText();
                  data[rowIndex][1] = txtName.getText();
                  data[rowIndex][2] = txtCourse.getText();
                  data[rowIndex][3] = txtProfessor.getText();
                  data[rowIndex][4] = txtHelp.getText();
                  data[rowIndex][5] = txtDate.getText();
                  data[rowIndex][6] = txtDate2.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();
   }
}

0 个答案:

没有答案