【发布时间】:2014-03-25 01:32:53
【问题描述】:
我正在学习 Java 的儿子(11 岁)将输入一个问题和一些代码。他告诉我他无法在网站上找到这个问题的答案。您将阅读我对他的问题的编辑版本。非常感谢。
如何在 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 获得了 keyconfigofplayer 的代码,我认为如何在 Java 第 12 集或第 11 集编程 GUI。我认为我的问题不在于更新图像,而在于检测何时按下然后释放该键。所以也许我应该做一个while循环说明: 如果按下此键,则 x 坐标 + 10 直到完成并不断更新位置。 我还想问一下,什么时候用public、private和void?我不明白那些:(如果我正确地完成了扩展播放器实现的事情。我试图仔细改变macheads101的代码,当我完全复制它时它也不起作用。所以我真的不知道出了什么问题。我会很感激的如果你回答了我的问题并帮助我修改了代码。最终它会成为一个射击游戏,就像街机游戏“太空入侵者”或“龙射击”。
【问题讨论】:
-
我知道使用 youtube 视频来学习东西很诱人,但它们确实不是编码的最佳解决方案。书面教程将允许您以更加可控的速度完成任务并查看实际代码。
-
哦,还有一件事。你可以在 Swing 中制作游戏,但你会发现你相当有限,因为它更多地是为商业类型软件设计的。要在 Java 中编写游戏,您需要一个图形库。例如本教程系列在 jME3 中制作了一个霓虹灯射手:gamedevelopment.tutsplus.com/tutorials/…
-
关于第一段我不得不说你是当年的家长。你的儿子有很大的编程潜力。继续鼓励他!
-
"我正在学习 Java 的儿子(11 岁)将输入一个问题和一些代码。他告诉我他无法在网站上找到该问题的答案。您将阅读我对他的问题的编辑版本。非常感谢。“干得好,用棍子打败了 COPPA!像你这样的人让世界运转起来。
标签: java eclipse swing keypress keylistener