使用jfilechooser保存照片通道并加载照片

时间:2016-12-01 01:02:53

标签: java mysql netbeans jfilechooser imageicon

我正在使用mySQL来存储我使用jFileChooser选择的照片目录。选择文件后,我将其保存到数据库中。但是当我检索数据并使用ImageIcon将标签设置为我保存的目录的照片时,它会显示一个nullpointer错误。

我在管理员中打开netbeans并且由于用户正在选择文件,因此文件必须存在,即不能指向null。

这是jFileChooser的代码:

    JFileChooser file = new JFileChooser();
      file.setCurrentDirectory(new File(System.getProperty("user.home")));
      FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");
      file.addChoosableFileFilter(filter);
      int result = file.showSaveDialog(null);
      if(result == JFileChooser.APPROVE_OPTION){
          File selectedFile = file.getSelectedFile();
          String path = selectedFile.getAbsolutePath();
          GlobalDataStore.imagepath=path;//this stores pathway so that i can save it to the database
          photofield.setIcon(ResizeImage(path));
      }

以及将其保存到数据库的代码

    String imagepath = GlobalDataStore.imagepath;// retrieves image directory
    {
        Class.forName("java.sql.DriverManager");
        Connection con = (Connection)DriverManager.getConnection(conndata,username,password);

        Statement stmt = (Statement)con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
        String query ="SELECT name,admn_no,class,section,house,gender,sloganstore,picturepath FROM candidates WHERE post=\""+GlobalDataStore.selectedpost+"\"";
        ResultSet rs = stmt.executeQuery(query);

        int rowcount = jTable1.getSelectedRow();
        for(;rs.getRow()<=rowcount;rs.next()){}

        rs.updateString("picturepath",imagepath);//saves it to the database

        rs.updateRow();
        JOptionPane.showMessageDialog(this, "data was successfully updated");
        con.close();
        deselect();

        DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
        int row = model.getRowCount();
        for(int i=0;i<row;i++){
        model.removeRow(0);
    }
    }

和将标签设置为图像的代码:

            String path=rs.getString("picturepath");
            con.close();
            System.out.println(path);
            ImageIcon photo=null;
            photo = new ImageIcon(getClass().getResource(path));
            photofield.setIcon(photo);

0 个答案:

没有答案