Issue
I am fairly new to Java so my knowledge is limited. I have this assignment where I have to get data from an Access database and fill a dialogBox full of fields. I had no problem with typical fields, but I hit a dead end trying to make the attachment field work.
I've tried using the .getByte() methods I've seen on the web, and I don't quite grasp yet the Attachment uncanaccess class method. Can anyone help me or guide me in the right direction please? Here's some code for reference on how I've filled the other fields:
JTextField_cod_distrib.setText(result.getLong("Cod_distribuitor")+"");
JCheckBox_in_stoc.setSelected(result.getBoolean("In_stoc"));
JTextField_pret.setText(result.getFloat("Pret")+""); JTextField_denumire_produs.setText(result.getString("Denumire_produs")+"");
JTextField_cod_produs.setText(result.getInt("Cod_produs")+"");
JTextField_ambalaj.setText(result.getString("Ambalaj")+"");
Solution
If you know that there is always exact one attachment in the array, you could do
jlabel.setIcon(new ImageIcon(getScaled(ImageIO.read(new ByteArrayInputStream(((Attachment[])result.getObject("attachment"))[0].getData())),120,120)));
Otherwise you will have to add a JLabel for every attachment:
JPanel attachmentPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
Attachment[] attachments=(Attachment[])result.getObject("attachment");
for(Attachment attachment:attachments) {
Image original=ImageIO.read(new ByteArrayInputStream(attachment.getData()));
attachmentPanel.add(new JLabel(new ImageIcon(getScaled(original,120,120))));
}
//add the attachmentPanel to your component
/**
*
* Resizes an image using a Graphics2D object backed by a BufferedImage.
* @param srcImg - source image to scale
* @param w - desired width
* @param h - desired height
* @return - the new resized image
*/
private BufferedImage getScaledImage(BufferedImage srcImg, int w, int h){
double sw=srcImg.getWidth();
double sh=srcImg.getHeight();
double fw=w/sw;
double fh=h/sh;
if(fw<fh) w=(int)(sw*fh);
else if(fh<fw) h=(int)(sh*fw);
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
Answered By - Sascha