I'm having a big problem when I save an image to the database.
I have a JLabel
called personImage
and when the user wants to insert an image, he has to click on personImage
, then a JFileChooser
appears and the user can select an image. The selected image will be loaded into personImage
.
When the user selects an image and saves it, it works properly, but when user doesn't select an image and is going to save the details, it gives a NullPointerException
. I think that is because there is no path to get the Image to File Object. How can I know whether there is a Image in JLabel
or not? I want to check if there's an image or not.
try {
String fname = txt_Fname.getText();
String lname = txt_Lname.getText();
String mobile = txt_mobile.getText();
String home = txt_home.getText();
String work = txt_work.getText();
String fax = txt_fax.getText();
byte[] image_detail;
PersonDAO perDAO = new PersonDAO(); //create person object
if (status == 1) // used status for check whether Jlabed is clicked
{
File image = new File(path);
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1; )
{
baos.write(buf, 0,readNum);
}
image_detail = baos.toByteArray();
Person person1 = new Person(fname, lname, mobile, home, work, fax, image_detail); // call the person
// constructer when there is an image. I did validate with status variable
perDAO.InsertPerson(person1); // call the personDAO to insert the Person to database
}
else
{
Person person2 = new Person(lname, lname, mobile, home, work, fax); // if there is not an image call this constructer .
perDAO.InsertPerson(person2); // then call to personDAO object to insert the person to databasee
}
}
catch (Exception exc)
{
System.out.println(exc + "sssssss");
}
// >>> when click on the JLabel, the JFileChooser appears
int i = jFileChooser2.showOpenDialog(this);
try {
f = jFileChooser2.getSelectedFile();
path = f.getAbsolutePath();
ImageIcon image = new ImageIcon(path);
status = 1;
personImage.setIcon(image);
}
catch (Exception exc)
{
System.out.println(exc);
}