我的11岁的儿子正在学习Java,他将要输入一个问题和一些代码。他告诉我在网站上没有找到这个问题的答案。您将会阅读我的编辑版本。非常感谢。
如何在Java中检测按键,我的IDE叫做Eclipse,我创建了一些类。我在互联网上找到了keyconfigofplayer内的代码,并将其更改为扩展播放器类。我希望当我按住某个键时,一个矩形或椭圆形图案可以在屏幕上移动,我该如何做呢?由于某种原因,它无法正确地输入代码,这就是为什么我的导入没有星号并且看起来很奇怪。对此我深感抱歉,请忽略它。我无法修复它:(。以下是我的代码:
窗口代码:
import javax.swing.*;
import java.awt.*;
public class window {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(600, 600);
player p = new player();
f.add(p);
keyconfigofplayer key = new keyconfigofplayer();
p.add(key);
f.add(key);
}
}
//this class is the player graphic
import javax.swing.*;
import java.awt.*;
public class player extends JPanel {
int x = 50;
int y = 50;
public void paint() {//This is where the graphic is painted to the screen
repaint();
}
public void paintComponent(Graphics g) {
//This is where the graphic is 'manufactured'
super.paintComponent(g);
g.setColor(Color.GREEN);
int width = 20;
int height = 20;
g.fillRect(x, y, width, height);
int width2 = 10;
int height2 = 10;
g.fillOval(x, y, width2, height2);
}
}
//the keyconfigofplayer class(where i think the problems are):
//this class is the player graphic
import javax.swing.*;
import java.awt.*;
public class player extends JPanel {
int x = 50;
int y = 50;
public void paint() {//This is where the graphic is painted to the screen
repaint();
}
public void paintComponent(Graphics g) {
//This is where the graphic is 'manufactured'
super.paintComponent(g);
g.setColor(Color.GREEN);
int width = 20;
int height = 20;
g.fillRect(x, y, width, height);
int width2 = 10;
int height2 = 10;
g.fillOval(x, y, width2, height2);
}
}
我已经尽力注释好类名,这样您就知道它们的意思了。 我从YouTube频道macheads101的Java GUI编程教程第12或11集中复制了keyconfigofplayer的代码。我认为我的问题不在于更新图片,而是在于检测何时按下并释放按键。因此,我应该使用while循环来说明: 如果按下此键,则将x坐标+ 10,直到完成,并不断更新位置。 我还想问,什么时候使用public、private和void?我不理解这些:(,以及我是否正确地执行了扩展玩家实现的操作。当我小心地改变macheads101的代码时,当我完全复制它时它也没有起作用。所以我真的不知道出了什么问题。如果您能回答我的问题并帮助我修改代码,我将不胜感激。最终它会成为一个类似于街机游戏“太空入侵者”或“龙之射手”的射击游戏。