首页 > 代码库 > Swing Panel 动画
Swing Panel 动画
一、实现原理:给panel添加两张图片,然后启动一个线程,不断的去重画这个panel,重画的过程中,改变这两张图片Y轴的坐标,这样就出现了图片滚动的效果。
二、代码:
package com.jack; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JPanel; import javax.swing.border.SoftBevelBorder; /** * * @author laughing * * @date 2014年11月16日 下午7:58:11 */ public class GamePanel extends JPanel implements Runnable { private int y = 0; private int y1 = -480; SoftBevelBorder border = new SoftBevelBorder(1, Color.white, Color.white); public GamePanel() { setBorder(border); } /* * (non-Javadoc) * * * * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) */ @Override protected void paintComponent(Graphics g0) { // TODO Auto-generated method stub super.paintComponent(g0); Graphics2D g = (Graphics2D) g0; try { Image image = ImageIO.read(this.getClass() .getResource("../../images/map.png")); Image image1 = ImageIO.read(this.getClass() .getResource("../../images/map_1.png")); if (image != null) { g.drawImage(image, 5, y, this); g.drawImage(image1, 5, y1, this); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { // TODO Auto-generated method stub while (true) { if (y == 480) { y = 0; } else { y += 10; } if (y1 == 0) { y1 = -480; } else { y1 += 10; } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } repaint(); } } }
package com.jack; import java.awt.GridLayout; import java.awt.List; import javax.swing.JFrame; /** * * @author laughing * @date 2014年11月16日 下午8:11:39 */ public class Main extends JFrame { GamePanel leftPanel = new GamePanel(); GamePanel centerPanel = new GamePanel(); List chartList = new List(); public Main() { setSize(800, 480); setLayout(new GridLayout(1, 3)); getContentPane().add(leftPanel); getContentPane().add(centerPanel); getContentPane().add(chartList); new Thread(leftPanel).start(); new Thread(centerPanel).start(); setVisible(true); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(this); } public static void main(String args[]) { new Main(); } }
三、代码下载
Swing Panel 动画
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。