Home  >  Article  >  Java  >  How to add pictures in java

How to add pictures in java

little bottle
little bottleOriginal
2019-05-22 16:18:4812537browse

本篇文章中将带大家学习一下用java代码实现在JPanel中添加一张图片,感兴趣的朋友可以了解一下。希望对你有所帮助。

How to add pictures in java

这里用到的是ImageIO类来加载图片

语句为:image=ImageIO.read(new File("H:\\aa.jpg"));

new File("")里是要添加的图片。

具体代码如下:

public class Test extends JFrame{    
    MyPanel mp=null;
    public Test(){
        mp=new MyPanel();
        this.add(mp);
        this.setSize(550, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }     
    public static void main(String[] args){
        new Test();
    }
} 
class MyPanel extends JPanel{     
    Image image=null;     
    public void paint(Graphics g){
        try {
            image=ImageIO.read(new File("H:\\aa.jpg"));//插入图片
            g.drawImage(image, 0, 0, 550, 400, null);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

The above is the detailed content of How to add pictures in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn