我对java比较陌生,并试图学习如何制作一个有这个圆圈的程序,我可以使用箭头键移动它。在通过一系列示例转换后,我能够将一些东西放在一起。虽然我不确定如何创建KeyEvent。对我所缺少的任何帮助都会很棒。
这是我到目前为止所做的。
import javax.swing.WindowConstants;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.KeyEvent;
@SuppressWarnings("serial")
public class Game extends JPanel
{
int x = 0;
int y = 0;
private void moveBallUP() {
x = x + 0;
y = y + 1;
}
private void moveBallDOWN() {
x = x + 0;
y = y - 1;
}
private void moveBallLEFT() {
x = x + 1;
y = y + 0;
}
private void moveBallRIGHT() {
x = x - 1;
y = y + 0;
}
@Override
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.red);
g2d.fillOval(y, x, 50, 50);
}
public static void main(String[] args) throws InterruptedException
{
JFrame frame = new JFrame("Sample Frame");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (event.getKeyCode() == KeyEvent.VK_UP)
{
game.moveBallUP();
game.repaint();
Thread.sleep(10);
}
if (event.getKeyCode() == KeyEvent.VK_DOWN)
{
game.moveBallDOWN();
game.repaint();
Thread.sleep(10);
}
if (event.getKeyCode() == KeyEvent.VK_LEFT)
{
game.moveBallLEFT();
game.repaint();
Thread.sleep(10);
}
if (event.getKeyCode() == KeyEvent.VK_RIGHT)
{
game.moveBallRIGHT();
game.repaint();
Thread.sleep(10);
}
}
}
答案 0 :(得分:0)
解决此问题有几个步骤:首先,使用KeyListener
。将以下代码添加到Game
类;这将代表按下哪些按钮:
private boolean upPressed=false;
private boolean downPressed=false;
private boolean leftPressed=false;
private boolean rightPressed=false;
然后,将其添加到main
方法:
frame.addKeyListener(new KeyListener() {
@Override
public void keyReleased(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.VK_UP:
game.upPressed=false;
break;
case KeyEvent.VK_DOWN:
game.downPressed=false;
break;
case KeyEvent.VK_LEFT:
game.leftPressed=false;
break;
case KeyEvent.VK_RIGHT:
game.rightPressed=false;
break;
}
}
@Override
public void keyTyped(KeyEvent event) {
}
@Override
public void keyPressed(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.VK_UP:
game.upPressed=true;
break;
case KeyEvent.VK_DOWN:
game.downPressed=true;
break;
case KeyEvent.VK_LEFT:
game.leftPressed=true;
break;
case KeyEvent.VK_RIGHT:
game.rightPressed=true;
break;
}
}
});
基本上,当按下按钮时,我们将创建的变量设置为true,释放按钮时将其设置为false。最后,在Timer
方法中添加main
:
Timer timer = new Timer(10,(e)->{
if (game.upPressed)
{
game.moveBallUP();
game.repaint();
}
if (game.downPressed)
{
game.moveBallDOWN();
game.repaint();
}
if (game.leftPressed)
{
game.moveBallLEFT();
game.repaint();
}
if (game.rightPressed)
{
game.moveBallRIGHT();
game.repaint();
}
});
timer.start();
如果按下按钮,这将每10毫秒触发一次并调用你的移动方法。
我已经对此进行了测试并知道它有效,但是您的移动方法会将方向移动到错误的方向。我想你可以解决这个问题。
编辑:错误在于此行:
g2d.fillOval(y, x, 50, 50);
将其更改为:
g2d.fillOval(x,y , 50, 50);