【发布时间】:2016-05-04 23:50:25
【问题描述】:
所以我尝试使用动画来旋转图像,方法是将图像更改为已旋转 22.5 度的新图像。我通过让 1 个类继承自 JFrame 和另一个类从 JPanel 继承来做到这一点但是它没有做任何事情。这是代码..
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.*;
public class LogoAnimatorJPanel extends JPanel implements ActionListener
{
protected ImageIcon[] images = new ImageIcon[16] ;
private int currentImage = 0;
private Timer animationTimer;
public LogoAnimatorJPanel()
{
for ( int count = 0; count < images.length; count++ ){
images [count] = new ImageIcon("car/yellowCar" + count + ".jpg");
}
startAnimation();
}
public void paintComponent( Graphics g )
{
super.paintComponent( g );
images[ currentImage ].paintIcon( this, g, 50 , 50 );
currentImage = ( currentImage + 1 ) % images.length;
}
public void startAnimation()
{
animationTimer = new Timer(20, this);
animationTimer.start();
}
public void actionPerformed( ActionEvent actionEvent )
{
repaint();
}
}
displayAnimator
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class displayAnimator extends JFrame
{
private LogoAnimatorJPanel fp;
public displayAnimator()
{
setTitle("car");
setBounds(200,200,200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(null);
fp = new LogoAnimatorJPanel();
fp.setBounds(180, 25, 100, 100);
cp.add(fp);
}
public static void main(String[] args)
{
displayAnimator testRun = new displayAnimator();
testRun.setVisible(true);
}
}
有什么想法吗?
【问题讨论】:
-
“有什么想法吗?” 1) 不要扩展
JFrame。更喜欢组合而不是继承。 2)在JLabel中显示图像(而不是JPanel) 3)不是设置框架的大小/边界,而是设置位置并在加载第一张图像后调用pack()。 4) 当显示一个涉及图像的示例时,热链接(Java 可以从 URL 加载图像)到在this Q&A 中看到的图像。 5) 在 EDT 上启动 GUI。 6) 应用程序资源在部署时将成为嵌入式资源,因此明智的做法是像现在一样开始访问它们.. -
.. embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。 7)
new ImageIcon("car/yellowCar" + count + ".jpg");使用ImageIO加载图像。ImageIcon将静默失败。 8) 使用@Override表示法对应该覆盖已定义方法的方法进行编译时检查。 9)cp.setLayout(null);Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。 .. -
.. 因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
标签: java image swing animation jpanel