我是编程初学者,我正在开发一款简单的游戏。
我想在JLabel
的每个位置之间制作一个计时器,所以它看起来很动画,虽然我无法弄清楚计时器方法是如何工作的。
感谢。
运动类:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.Timer;
public class movement
{
private JComponent jt;
private InputMap ip;
private ActionMap ap;
private String comm;
private KeyStroke key;
private int movement;
public movement(JComponent jt, InputMap ip,ActionMap ap, String comm,KeyStroke key,int movement)
{
this.jt = jt;
this.ip = ip;
this.ap= ap;
this.comm = comm;
this.key = key;
this.movement = movement;
}
public void newAction()
{
this.ip = this.jt.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
this.ip.put(key, comm);
this.ap = this.jt.getActionMap();
this.ap.put(this.comm, new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
int originaly = jt.getY();
if(key == KeyStroke.getKeyStroke(KeyEvent.VK_UP,0))
{
Timer t = new Timer(100, this);
t.setRepeats(false);
jt.setBounds(jt.getX(),jt.getY()+movement , 50, 50);
t.start();
if(originaly<=jt.getY()+50)
{
t.stop();
}
}
else
{
jt.setBounds(jt.getX()+movement,jt.getY() , 50, 50);
}
}
});
}
}
这是我的主要方法。我之前遇到过一些问题,但我认为现在好了,这不是问题。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.beans.PropertyChangeListener;
import java.net.MalformedURLException;
import java.net.URL;
import javax.management.openmbean.KeyAlreadyExistsException;
import javax.swing.*;
import java.util.concurrent.TimeUnit;
public class Malario
{
public static void main(String[] args)
{
JFrame frame = new JFrame("malario");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(700, 700);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.blue);
JLabel malario = new JLabel("Malario");
malario.setOpaque(true);
malario.setBackground(Color.green);
panel.add(malario);
malario.setBounds(100, 550, 50, 50);
JLabel platform = new JLabel();
platform.setOpaque(true);
platform.setBounds(0,600,700,50);
panel.add(platform);
frame.setContentPane(panel);
final int originalx = 100;
final int originaly = 550;
int currentlocx = originalx;
int currentlocy = originaly;
movement moveRight = new movement(malario, new InputMap(), new ActionMap(), "move Right",KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0) , 10);
movement moveLeft = new movement(malario, new InputMap(), new ActionMap(), "move Left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0), -10);
movement jumpUp = new movement(malario, new InputMap(), new ActionMap(), "move Up", KeyStroke.getKeyStroke(KeyEvent.VK_UP,0), -10);
moveRight.newAction();
moveLeft.newAction();
jumpUp.newAction();
}
}