import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Game extends JPanel {
Ball ball = new Ball(this);
Number123 num123 = new Number123(this);
public Game(){
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
ball.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
ball.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
num123.paintComponent(g2d);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Two sprites");
Game game = new Game();
frame.add(game);
frame.setSize(600, 800);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Ball implements ActionListener, KeyListener{
int x = 0;
int y = 0;
int xa = 0;
int ya = 0;
private Game game;
public Ball(Game game){
this.game= game;
}
void move(){
if (x + xa > 0 && x + xa < game.getWidth()-60)
x = x + xa;
if (y + ya > 0 && y + ya < game.getHeight()-60)
y = y + ya;
}
public void paint(Graphics2D g){
g.fillOval(x, y, 30, 30);
}
public void keyReleased(KeyEvent e) {
if (xa == 1){
xa = 1;}
if (xa == -1){
xa = -1;
}
if (ya == 1){
ya = 1;}
if (ya == -1){
ya = -1;
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
if (e.getKeyCode() == KeyEvent.VK_UP)
ya = -1;
if (e.getKeyCode() == KeyEvent.VK_DOWN)
ya = 1;
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
java的新手如果它是一个简单的答案那么对不起。
当我运行程序时,我的圆形对象以不垂直和水平的角度移动。
答案 0 :(得分:1)
当您想要垂直移动时,需要将xa
设置为0,当您想要水平移动时,需要将ya
设置为0。它们以这种方式初始化,但永远不会被重置。