Ich möchte ein Bild (hier ist Rechteck) in Applet, Applet zieht es, aber ich frage mich, warum das Bild nicht bewegt? Es gibt keinen Kompilierfehler!Bild bewegt sich nicht in Applet
hier ist mein Code:
package game;
import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Gamer extends JApplet implements KeyListener
{
private int x=50,y=50;
@Override
public void init()
{
addKeyListener(this);
}
@Override
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
switch(keyCode)
{
case KeyEvent.VK_UP:
if(y>0) //when up key is pressed and the position of the player is not on the edge
{
y=y-19;
repaint();
}
break;
case KeyEvent.VK_DOWN:
if(y<171) //when down key is pressed and the position of the player is not on the edge
{
y=y+19;
repaint();
}
break;
case KeyEvent.VK_LEFT:
if(x>0)
{
x=x-15;
repaint();
}
break;
case KeyEvent.VK_RIGHT:
if(x<285)
{
x=x+15;
repaint();
}
break;
}
}
@Override
public void paint(Graphics g) //will draw the background and the character
{
g.fillRect(x, y, 200, 200);
}
@Override
public void keyReleased(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
}
Als ich nach oben gedrückt/unten/links/Schreib Pfeil, wird das Rechteck nicht bewegt. Bitte erklären warum? T.I.A.
1) Warum ein Applet codieren? Wenn es aufgrund der Angabe des Lehrers geschieht, verweisen Sie bitte auf [Warum CS-Lehrer ** aufhören sollten ** Java-Applets zu unterrichten] (http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should -stop-teaching-Java-Applets /). 2) Siehe [Java Plugin-Unterstützung nicht mehr unterstützt] (http://www.gizmodo.com.au/2016/01/rest-in-hell-java-plug-in/) und [Wechsel zu einem Plugin-freien Web] (https://blogs.oracle.com/java-platform-group/entry/moving_to_a_plugin_free). 3) Für Swing verwenden wir typischerweise [key bindings] (https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) statt 'KeyListener'. –