问题是我的gif叫" grrass"在程序中应该自动移动,但只有当我按下按钮时它才会移动。
这是我创建框架的主要类以及创建窗口所需的东西:
import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class mainCalss {
public static void main (String args[]) {
JFrame f = new JFrame();
second d = new second();
f.add(d);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1200 , 900);
}
}
这是我的方法类,它包含我的gif图像和我的主要运行过程:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
public class second extends JPanel implements ActionListener , KeyListener {
Image img = Toolkit.getDefaultToolkit().createImage("images/grrass.gif");
Timer t = new Timer(90, this);
int x = 0 , y = 0 , velx = 0 , vely = 0 ;
public second () {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(img, 0,0, null);
g2.fill(new Ellipse2D.Double(100+x , 100+y, 30 , 30));
g2.drawRect(x+100, y+100, 30, 30);
g2.fillRect(x+115, y+112, 50 , 2);
g2.fillRect(x+115, y+118, 50 , 2);
g2.setColor(Color.yellow);
g2.fillOval(x-10, 10+y, 50, 50);
g2.fillRect(x-10, y+8, 70, 40);
g2.setColor(Color.black);
g2.drawRect(x-10, y+8, 70, 40);
g2.drawOval(x-10, 10+y, 50, 50);
g2.setColor(Color.yellow);
g2.fillOval(x, y, 200, 100);
g2.setColor(Color.black);
g2.drawOval(x, y, 200, 100);
g2.drawLine(x+0,y+50,x+200,y+50);
g2.drawOval(x, 20+y, 200, 60);
}
public void actionPerformed(ActionEvent e) {
if(x<0)
x+=35;
if(y<0)
y+=35;
if(x>1100)
x-=135;
if(y>650)
y-=30;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN: y += 20; break;
case KeyEvent.VK_UP: y += -20; break;
case KeyEvent.VK_LEFT: x += -20; break;
case KeyEvent.VK_RIGHT: x += 20; break;
}
repaint();
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
}
}