I have a java based epos system in use within my company and am presently writing a series of Java apps for use in the back office / warehouse. The purpose of my current project is to extract an Image (saved as a blob), and a title (varchar value) from MYSQL and display each of these on JLabels within a JPanel.
First the sql query is handled within a class called DataLogic like so:
public class DataLogic {
MySQLConnect mysqlConnect = new MySQLConnect();
private Connection connect = null;
private PreparedStatement preparedStatement = null;
public ResultSet getCategories(){
try {
connect = mysqlConnect.connDatabase();
preparedStatement = connect.prepareStatement("SELECT image, name, texttip from CATEGORIES ORDER BY name");
ResultSet resultSet = preparedStatement.executeQuery();
return resultSet;
} catch (Exception e){
}
return null;
}
}
AS you can see the get Categories function returns a ResultSet which is used in the populateCats() function of a class called GuiEvents, the relevant section of which is below:
public void populateCats(){
results = dataLogic.getCategories();
try{
int count = 0;
while (results.next()) {
++count; // Get data from the current row and use it
}
results.first();
while (results.next()){
GridLayout catLayout = new GridLayout(count,2);
System.out.println(count);
gui.catList.setLayout(catLayout);
JLabel catLabel = new JLabel(results.getString(2));
JLabel imgLabel = new JLabel();
imgLabel.setIcon(displayImage(results.getBytes(1)));
gui.catList.add(imgLabel);
gui.catList.add(catLabel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public ImageIcon displayImage(byte[] bytes) {
Image img = Toolkit.getDefaultToolkit().createImage(bytes);
// new code
int imgHeight = img.getHeight(null);
int imgWidth = img.getWidth(null);
int newHeight = imgHeight / 2;
int newWidth = imgWidth / 2;
//System.out.println(imgHeight + "," + imgWidth);
Image resizedImg = img.getScaledInstance(40,40,Image.SCALE_SMOOTH );
//end new code
ImageIcon icon = new ImageIcon(resizedImg);
return icon;
}
My problem is that although it compiles and runs i get the following error within netbeans:
java.lang.NullPointerException
at java.awt.Toolkit.createImage(Toolkit.java:1111)
at gapricing.app.first.GuiEvents.displayImage(GuiEvents.java:48)
at gapricing.app.first.GuiEvents.populateCats(GuiEvents.java:39)
at gapricing.app.first.Gui.<init>(Gui.java:111)
at gapricing.app.first.Main.main(Main.java:6)
and whilst 29 of the images and titles are displayed exactly as I would have liked the remianing 9 do not although thanks to the gridlayout 9 empty boxes are included at the bottom of the JPanel. Can anyone help pls??
bytesmight be null.