Java - 无法从文件中绘制图像

时间:2014-02-23 16:22:12

标签: java image swing file draw

我使用NetBeans,我想在jPanel上显示图像(基本上是为了使其滚动)。 我写了这段代码

    Graphics g=jPanelScrolling.getGraphics();
    File fileBackground = new File("background.jpg");
    Image background;
    try{
        background=ImageIO.read(fileBackground);
        final int WIDTH=background.getWidth(rootPane);            
        final int HEIGHT=background.getHeight(rootPane);
        g.drawImage(background, WIDTH, HEIGHT, rootPane);
    }
    catch(IOException e){
        background=null;
        jPanelScrolling.setBackground(Color.red);  //to test if the image has been succesfully uploaded
    }

但是当我执行它时,它只向我显示void jPanel

我怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:1)

尝试,

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageInFrame {
    public static void main(String[] args) throws IOException {
        String path = "Image1.jpg";
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        JLabel label = new JLabel(new ImageIcon(image));
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(label);
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
    }
}

答案 1 :(得分:1)

想要显示图片,请尝试以下方式:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImagePanel extends JPanel{
    private BufferedImage bi;

    public ImagePanel() {  

      try {
            bi = ImageIO.read(new File("Your Image Path"));
        } catch (IOException ex) {
            Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex);
        }


        final JPanel panel = new JPanel(){
            @Override
            protected void paintComponent(Graphics g){
                Graphics g2 = g.create();
                g2.drawImage(bi, 0, 0, getWidth(), getHeight(), null);
                g2.dispose();
            }

            @Override
            public Dimension getPreferredSize(){
                return new Dimension(bi.getWidth()/2, bi.getHeight()/2);
                //return new Dimension(200, 200);
            }
        };

        add(panel);
    }  

        public static void main(String args[]){
            SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ImagePanel imgPanel=new ImagePanel();
                JOptionPane.showMessageDialog(
                        null, imgPanel, "Image Panel", JOptionPane.PLAIN_MESSAGE);
            }
        });
        }
}

<强>输出

Image