JAVA Frame 窗体背景图片,首位相接滚动代码实例
背景图片连续滚动,程序已经跑过。前提!背景图片宽度比窗体长些,代码如下:
importJava.awt.Graphics; importjava.awt.Image; importjavax.swing.ImageIcon; importmine.game.util.PropertiesUtil; @SuppressWarnings("serial") publicclassGameFrameextendsMyFrame{ privateImageimg=ImageUtil.imageLoad("image/bk.jpg"); doublemovs,speed=1,headmovs; doublepWidth,pHeight,bgWidth; @Override publicvoidpaint(Graphicsg){ //g.drawImage(img,0,0,null); //=================================================== pWidth=PropertiesUtil.getValue("Width","game.properties"); pHeight=PropertiesUtil.getValue("Height","game.properties"); bgWidth=newImageIcon(img).getIconWidth(); //movs+=speed; if(bgWidth>pWidth+movs){ g.drawImage(img,0,0,(int)pWidth,(int)pHeight,(int)movs,0,(int)(pWidth+movs),(int)pHeight,null); } if(bgWidth<=pWidth+movs){ headmovs=pWidth+movs-bgWidth; g.drawImage(img,0,0,(int)(pWidth-headmovs),(int)pHeight,(int)movs,0,(int)(bgWidth),(int)pHeight,null); g.drawImage(img,(int)(pWidth-headmovs),0,(int)pWidth,(int)pHeight,0,0,(int)(headmovs),(int)pHeight,null); if(headmovs>=pWidth){ //重新初始化所有变量数据,循环 movs=headmovs-pWidth; } } movs+=speed; //=================================================== } publicstaticvoidmain(String[]args){ GameFramegf=newGameFrame(); gf.launchFrame(); } } //================================= importjava.awt.Frame; importjava.awt.Graphics; importjava.awt.event.WindowAdapter; importjava.awt.event.WindowEvent; importjava.awt.image.BufferedImage; importmine.game.util.PropertiesUtil; @SuppressWarnings("serial") publicclassMyFrameextendsFrame{ privateBufferedImageimgBuffer; privateGraphicsgBuffer; publicvoidlaunchFrame(){ intwd=800;//PropertiesUtil.getValue("Width","game.properties"); intht=600;//PropertiesUtil.getValue("Height","game.properties"); setSize(wd,ht); setLocation(0,0); setVisible(true); newPaintThread().start(); addWindowListener(newWindowAdapter(){ @Override publicvoidwindowClosing(WindowEvente){ System.exit(0); } }); } //重画窗口线程,内部类 classPaintThreadextendsThread{ publicvoidrun(){ while(true){ repaint(); try{ Thread.sleep(10); }catch(InterruptedExceptione){ e.printStackTrace(); } } } } /** *双缓冲解决,屏闪.此方法在,继承Frame的AWT编程中才有效。JFram不凑效,其有自己先进的实现方式(自己猜的,有时间学学) */ @Override publicvoidupdate(Graphicsg){ if(imgBuffer==null){ imgBuffer=(BufferedImage)createImage(this.getWidth(),this.getSize().height);//创建图形缓冲 //imgBuffer=newBufferedImage((int)this.getSize().getWidth(),(int)this.getSize().getHeight(),BufferedImage.TYPE_4BYTE_ABGR);//创建图形缓冲 } gBuffer=imgBuffer.getGraphics();//获取图形缓冲区的图形上下文 gBuffer.fillRect(0,0,this.getWidth(),this.getHeight()); this.paint(gBuffer);//用paint方法中编写的绘图过程对图形缓冲区绘图 gBuffer.dispose();//释放图形上下文资源 g.drawImage(imgBuffer,0,0,null);//将图形缓冲区绘制到屏幕上 } } //==================== importjava.awt.Image; importjava.awt.Toolkit; importjava.NET.URL; publicclassImageUtil{ publicstaticImageimageLoad(Stringpath){ URLu=ImageUtil.class.getClassLoader().getResource(path); returnToolkit.getDefaultToolkit().getImage(u); } }
希望以上内容代码对您有所帮助