动画在Java中的两个图像 [英] Animating two images in java
问题描述
我很新的到Java。我需要在Java游戏动画两个图像。它的意思是一个飞船游戏允许两个用户控制的对象,使用键盘。我已经部分地实现这一点,但我不明白如何让两个键盘控制,也就是通过键盘输入移动一个对象闪烁了很多。
I'm quite new to java. I need to animate two images on a java game. It's meant to be a spaceship game allowing two users to control the objects, using a keyboard. I've partially implemented this, however I cannot understand how to allow for two keyboard controls, and also the one object that is moving via keyboard input is flickering a lot.
public class MainFrame extends JFrame implements KeyListener {
MainPanel mPanel;
MainPanel secondss;
MainPanel thirdss;
int speed = 5;
//ss facing north
int direction = 0;
MainFrame() {
setTitle("spaceship Game");
mPanel = new MainPanel("C:/img");
secondss = new MainPanel("C:/img");
setSize(1024, 768);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(mPanel); // add MainPanel JPanel to JFrame
setVisible(true); // show class
add(secondSs);
add(thirdSs);
seconds.currentSs.setX(400);
secondSS.currentSs.setY(100);
}
public void actionPerformed( ActionEvent e )
{
if( e.getSource() == mPanel)
{
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == e.VK_LEFT) {
int x = mPanel.currentSs.getX() - speed;
mPanel.currentSs.setX(x);
}
if (e.getKeyCode() == e.VK_RIGHT) {
int x = mPanel.currentSs.getX() + speed;
mPanel.currentSs.setX(x);
}
if (e.getKeyCode() == e.VK_DOWN) {
int y = mPanel.currentSs.getY() + speed;
mPanel.currentSs.setY(y);
}
if (e.getKeyCode() == e.VK_UP) {
int y = mPanel.currentSs.getY() - speed;
mPanel.currentSs.setY(y);
}
//change image direction
mPanel.frame = direction;
}
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
mainFrame.addKeyListener(mainFrame);
}
如果有人可以提供帮助或如果不点我在正确的方向我将不胜感激。
If someone could provide help or if not point me in the right direction I would be grateful.
推荐答案
-
JFrame中不可作为焦点的KeyEvent为,则默认情况下从未到的KeyEvent反应
JFrame isn't focusable for KeyEvents, then by default never to react to KeyEvents
调用setVisible(真);应该是最后code线,毕竟JComponent上被添加到JFrame中,
setVisible(true); should be last code line, after all JComponents are added to JFrame,
为什么原因是有公共无效的actionPerformed(ActionEvent的五),必须产生错误时抛出的形式compilier
for why reason is there public void actionPerformed( ActionEvent e ), must generating excpetion form compilier
-
创建一个JFrame作为局部变量
create a JFrame as local variable
提出的JPanel进入的JFrame
put JPanel into JFrame
覆盖GET preferredSize的JPanel的,为的JFrame的setSize的instesad
override getPreferredSize for JPanel, instesad of setSize for JFrame
然后调用包()和setVisble(真)
then call pack() and setVisble(true)
-
把图像Java包
put images to the Java package
把图像至的JLabel
put Images to JLabel
设置为NullLayout JPanel的(否则动画是不可能的)
set NullLayout to JPanel (otherwise animations isn't possible)
添加键盘绑定的JPanel,覆盖所需/所需的KeyEvent
add KeyBindings to JPanel, override desired/required KeyEvents
- 有通过使用自定义的绘画,通过重写paintComponent为JPanel的另一种方式,对于这里的KeyEvent保持键绑定为更好的倾听与KeyListener的比较
这篇关于动画在Java中的两个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-