如何从Access附件字段中提取图像并将其放置在JLabel中

时间:2019-05-22 16:53:51

标签: java netbeans resultset ucanaccess

我对Java相当陌生,所以我的知识有限。我需要从Access数据库中获取数据并填充一个充满字段的对话框。我对典型字段没有问题,但是尝试使附件字段正常工作时我走到了尽头。

我尝试使用在网络上看到的.getByte()方法,但我还不太了解Attachment uncanaccess类方法。谁能帮助我或指导我正确的方向?以下是一些有关我如何填写其他字段的参考代码:

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")+"");  

1 个答案:

答案 0 :(得分:1)

如果您知道数组中始终只有一个附件,则可以

jlabel.setIcon(new ImageIcon(getScaled(ImageIO.read(new ByteArrayInputStream(((Attachment[])result.getObject("attachment"))[0].getData())),120,120)));

否则,您将必须为每个附件添加一个JLabel:

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

来自https://docs.oracle.com/javase/tutorial/uiswing/examples/components/IconDemoProject/src/components/IconDemoApp.java

/**
     * 
     * 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 Image getScaledImage(Image srcImg, int w, int h){
        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;
    }