Table of contents
2. Display the picture in the interface
1. Get the picture first
There are many ways to load pictures, I will only introduce one here, after all, there are too many ways to remember.
URL url1=deskball.class.getClassLoader().getResource("desk_bacll/image/desk.png"); URL url2=deskball.class.getClassLoader().getResource("desk_bacll/image/ball.png"); //参数是路径 Image desk= ImageIO.read(url1);//这里的的参数是URL类型 Image ball=ImageIO.read(url2);
2. Display the picture in the interface
Regarding the display of pictures, a paint() method is used here. For the paint() method we need to rewrite it ourselves. The paint() method does not need us to call, the system will call it automatically, we must remember that he does not need us to call.
public st extends JFrame{ @Override public void paint(Graphics g) { g.drawImage(desk,0,0,856,501,null); //第一个参数就是image图片 //第二个以及第三个参数是图片显示的位置 //第四第五表示的是大小(宽度和高度) //最后一个参数可以当成死记硬背只要写null就行 g.drawImage(ball,100,100,30,30,null); } }
3. Complete code display
public class deskball extends JFrame { URL url1=deskball.class.getClassLoader().getResource("desk_bacll/image/desk.png"); URL url2=deskball.class.getClassLoader().getResource("desk_bacll/image/ball.png"); Image desk= ImageIO.read(url1); Image ball=ImageIO.read(url2); @Override public void paint(Graphics g) { g.drawImage(desk,0,0,856,501,null); g.drawImage(ball,100,100,30,30,null); } public deskball() throws IOException { this.setSize(856,501); this.setLocation(100,100); setVisible(true); } //重写画图类 }
//程序入口 public class Test { public static void main(String[] args) throws Exception { new deskball(); } }