2017年7月29日 星期六

(Java) 資料庫


程式碼 :





import java.awt.Color;
import java.io.*;
import java.util.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author user
 */
public class DataCollect extends javax.swing.JFrame {
    static List<Commodity> o =  new ArrayList<Commodity>();
    static List<String> Mod = new ArrayList();
    Sio sio = new Sio();
    static ADD obj = new ADD();
    static int i ;
    /**
     * Creates new form DataCollect
     */
    /*public void OutSio(){
        for(Commodity c : o){
                            jComboBox1.addItem(c.name);
                            sio.jTextField1.setText(c.name);
                            sio.jTextField4.setText(c.ID);
                            sio.jTextField2.setText(c.price.toString());
                            sio.jTextField3.setText(c.unit);
                            sio.jTextField5.setText(c.count.toString());
                            sio.jLabel8.setText(c.toString());
                        }
                         
    }*/
 
    public DataCollect() throws IOException {
        initComponents();
        //讀取 與 匯入名稱至ComboBox1
          Read();
         for(Commodity c : o)   {jComboBox1.addItem(c.name);}
   
   //  事件
         obj.jButton1.addActionListener(new java.awt.event.ActionListener() {//第一筆添加沒有問題,但第二次添加會跑出兩次視窗和添加了2次,之後再添加依此類推
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    int close = JOptionPane.showConfirmDialog(
                            JOptionPane.getRootFrame(),
                            "確定要儲存嗎?",
                            "警告",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE);
                 
                    if (close == JOptionPane.YES_OPTION)
                        add(); //經過確認後才進行資料添加
                    obj.dispose();
                } catch (IOException ex) {
                    Logger.getLogger(DataCollect.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

  //------------------------

  sio.jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    o.get(i).name = sio.jTextField1.getText();
                    jComboBox1.removeItemAt(i);
                    jComboBox1.addItem( o.get(i).name);
                    o.get(i).ID =  sio.jTextField4.getText();
                    o.get(i).price = Integer.parseInt(sio.jTextField2.getText());
                    o.get(i).unit = sio.jTextField3.getText();
                    o.get(i).count = Integer.parseInt(sio.jTextField5.getText());write();i =0;
                } catch (IOException ex) {
                    Logger.getLogger(DataCollect.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
  //------------------------------
  sio.jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                        int close = JOptionPane.showConfirmDialog(
                            JOptionPane.getRootFrame(),
                            "確定要刪除嗎?",
                            "警告",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE);
                 
                    if (close == JOptionPane.YES_OPTION){
                            try {
                                jComboBox1.removeItemAt(i);
                                o.remove(i);write();i =0;sio.dispose();
                            } catch (IOException ex) {
                                Logger.getLogger(DataCollect.class.getName()).log(Level.SEVERE, null, ex);
                            }
                    }                
            }
        });
    }
 
 void Read() throws IOException{
 File data = new File("SHOP/列表.txt");
 if(data.exists()){//檢查是否存在
BufferedReader Data = new BufferedReader(new  InputStreamReader(new FileInputStream("SHOP/列表.txt"),"big5"));
String inData;
int i = 0;
while((inData = Data.readLine()) != null){
Scanner s = new Scanner(inData ).useDelimiter("\t");
o.add(new Commodity());
o.get(i).name = s.next();
o.get(i).ID = s.next();
o.get(i).price =   s.nextInt();
o.get(i).unit = s.next();
o.get(i).count= s.nextInt();
o.get(i).time = s.next();
i++;
}
Data.close();
                     
 }else{
// out.println("*******請開始建立資料*******");
 File data2 = new File("SHOP");
 data2.mkdirs();
 }
       //   Collections.sort(o);
  }
    //------------------------------------------------

    void add() throws IOException{     //添加資料方法 o.add(new Commodity()); 加入集合後,Mod.add(o.get(o.size()-1).name);檢查確實有出來 ,但經過write方法 顯示o集合內沒有值
 o.add(new Commodity());
o.get(o.size()-1).name = obj.jTextField1.getText();
                 
//out.print("請輸入編號:");
              if(!obj.jTextField4.getText().isEmpty())
o.get(o.size()-1).ID = obj.jTextField4.getText();
              else
                o.get(o.size()-1).ID = "xxx";
//out.print("請輸入價格:");
              if(!obj.jTextField2.getText().isEmpty()&&obj.jTextField2.getText().matches("\\d*"))
o.get(o.size()-1).price = Integer.parseInt(obj.jTextField2.getText());
              else
                 o.get(o.size()-1).price = 0;
//out.print("請輸入單位:");
              if(!obj.jTextField3.getText().isEmpty())
o.get(o.size()-1).unit = obj.jTextField3.getText();
              else
                 o.get(o.size()-1).unit = "xxx";
//out.print("請輸入數量:");
              if(!obj.jTextField5.getText().isEmpty()&&obj.jTextField5.getText().matches("\\d*"))
o.get(o.size()-1).count= Integer.parseInt(obj.jTextField5.getText());
                else
                 o.get(o.size()-1).count = 0;
//out.println("添加完畢");
                //Collections.sort(o);
                Mod.add(o.get(o.size()-1).name);
 
                jComboBox1.addItem(o.get(o.size()-1).name);
               // obj.setVisible(true);
           
         
             write();
  }
    //-------------------------------------------------
    static void write() throws IOException{
 BufferedWriter Data = new BufferedWriter(new FileWriter("SHOP/列表.txt"));
 for(Commodity c : o){
   Data.write(c.name+"\t");
   Data.write(c.ID+"\t");
   Data.write(c.price+"\t");
   Data.write(c.unit+"\t");
   Data.write(c.count+"\t");
   Data.write(c.time+"\r\n");//txt要+\r\n 不然無法換行 %也是
   }
       
Data.close();
//out.println("Finsh @ ***");
  }
 
 
 
 
 
 
 
 
 
    /**
     * 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() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox<>();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(681, 443));
        getContentPane().setLayout(null);

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setFont(new java.awt.Font("標楷體", 0, 24)); // NOI18N
        jRadioButton1.setForeground(new java.awt.Color(255, 51, 0));
        jRadioButton1.setText(" $");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jRadioButton1);
        jRadioButton1.setBounds(345, 291, 49, 39);

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setFont(new java.awt.Font("標楷體", 0, 18)); // NOI18N
        jRadioButton2.setForeground(new java.awt.Color(0, 0, 204));
        jRadioButton2.setText("數量");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jRadioButton2);
        jRadioButton2.setBounds(345, 250, 61, 31);

        jPanel2.setBackground(new java.awt.Color(51, 204, 255));
        jPanel2.setLayout(null);

        jButton1.setFont(new java.awt.Font("標楷體", 0, 24)); // NOI18N
        jButton1.setText("添加");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);
        jButton1.setBounds(32, 107, 157, 35);

        jComboBox1.setFont(new java.awt.Font("標楷體", 0, 18)); // NOI18N
        jPanel2.add(jComboBox1);
        jComboBox1.setBounds(32, 46, 157, 43);

        jButton3.setFont(new java.awt.Font("標楷體", 0, 24)); // NOI18N
        jButton3.setText("查看");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);
        jButton3.setBounds(32, 176, 157, 39);

        jButton2.setFont(new java.awt.Font("標楷體", 0, 24)); // NOI18N
        jButton2.setText("中文");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(30, 230, 160, 30);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/20150000-0002.JPG"))); // NOI18N
        jLabel2.setText("jLabel2");
        jPanel2.add(jLabel2);
        jLabel2.setBounds(0, 0, 260, 410);

        getContentPane().add(jPanel2);
        jPanel2.setBounds(424, 0, 267, 597);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(null);

        jTextArea1.setBackground(new java.awt.Color(102, 255, 255));
        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("標楷體", 0, 13)); // NOI18N
        jTextArea1.setForeground(new java.awt.Color(255, 51, 51));
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(10, 10, 290, 380);

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lighthouse-658933_960_720.jpg"))); // NOI18N
        jLabel4.setText("jLabel4");
        jPanel1.add(jLabel4);
        jLabel4.setBounds(-20, -20, 340, 430);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(0, 0, 320, 440);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/史丹佛016.jpg"))); // NOI18N
        jLabel1.setText("jLabel1");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(-5, -30, 760, 470);

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
     
        obj.setVisible(true);
     
     
   
     
    }                                      
   
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        sio.setVisible(true);
        String n = (String)jComboBox1.getSelectedItem();
       
        for( i =0 ; i < o.size() ; i++) {
             if(n.equals(o.get(i).name)){
                            sio.jTextField1.setText(o.get(i).name);
                            sio.jTextField4.setText(o.get(i).ID);
                            sio.jTextField2.setText(o.get(i).price.toString());
                            sio.jTextField3.setText(o.get(i).unit);
                            sio.jTextField5.setText(o.get(i).count.toString());
                            sio.jLabel8.setText(o.get(i).time);break;   }
                     }
     
     
     
     
     
    }                                      

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        //COPY
        if(jRadioButton2.isSelected()){
        List<Commodity> oi =  new ArrayList<Commodity>(Arrays.asList(new Commodity[o
    .size()]));
     Collections.copy(oi,o);
        //----
     Collections.sort(oi);
     jTextArea1.append("ID排列---------------------\n");
        for(Commodity oio : oi ){
          jTextArea1.append("商品名 :"+oio.name+"\nID :"+oio.ID+"\n價格 :"+oio.price+"\n單位 :"+oio.unit+"\n數量 :"+oio.count+
                  "\n-------------"+oio.time+"-------------------\n");
        }
        }
    }                                          

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
         if(jRadioButton1.isSelected()){        
             List<Commodity> oi =  new ArrayList<Commodity>(Arrays.asList(new Commodity[o
    .size()]));
           Collections.copy(oi,o);
             for(int j = 0 ; j < o.size() ; j++){
                 for(int k = j+1 ; k < o.size() ; k++){
                     if(oi.get(j).price < oi.get(k).price ){
                      int y =  oi.get(j).price  ;
                      oi.get(j).price = oi.get(k).price;
                      oi.get(k).price = y;
                     }
                 }
             }
             jTextArea1.append("price排列---------------------\n");
              for(Commodity oio : oi ){
          jTextArea1.append("商品名 :"+oio.name+"\nID :"+oio.ID+"\n價格 :"+oio.price+"\n單位 :"+oio.unit+"\n數量 :"+oio.count+
                  "\n-------------"+oio.time+"-------------------\n");
        }
         }      
    }                                          
xin x = new xin();
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        x.setVisible(true);
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws IOException {
        /* 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(DataCollect.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DataCollect.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DataCollect.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DataCollect.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() {
                try {
               
                 
                    new DataCollect().setVisible(true);
                 
                } catch (IOException ex) {
                    Logger.getLogger(DataCollect.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
   
    }

    // Variables declaration - do not modify                  
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox<String> jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration                
}
class Commodity  implements Comparable<Commodity>{
Date date = new Date();
String name;
String ID;
Integer price;
String unit;
Integer count ;
String time = String.format("%tF %<tT",date) ;
@Override
public int compareTo(Commodity arg0){
return count.compareTo(arg0.count);
}

}

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。