我正在用Java自学2D图形。我正在尝试创建一个块堆叠游戏。到目前为止,我能够让第一行移动和停止,但我的目标是在第一行下方生成一个新行,而第一行保持原位。我感觉就像修复这个是一个我还没有学到的简单概念。但是,任何建议将不胜感激。如果你想让我指向正确的方向,我可以自学二维图形,我也会很感激。
我的JFrame代码如下:
public class BlockStacker extends JFrame {
public class AL extends KeyAdapter {
stack2 s2 = new stack2();
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
}
}
public static void main(String[] args){
stack2 s = new stack2();
JFrame f = new JFrame();
f.add(s);
f.setVisible(true);
f.setSize(1920, 1080);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Block Stacker");
}
}
带有图形和keylistener的代码是这样的:
public class stack2 extends JPanel implements ActionListener, KeyListener{
Timer t = new Timer(250, this);
double x, y, velX = 253;
public stack2() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
setBackground(Color.BLACK);
Color blue = new Color(0,0,255);
g2.setColor(blue);
Rectangle2D.Double rectangle = new Rectangle.Double(x + 210, y, 200, 100);
g2.fill(rectangle);
Rectangle2D.Double rectangle2 = new Rectangle.Double(x, y, 200, 100);
g2.fill(rectangle2);
Rectangle2D.Double rectangle3 = new Rectangle.Double(x + 420, y, 200, 100);
g2.fill(rectangle3);
}
public void actionPerformed(ActionEvent e) {
if (x < 0) {
velX = -velX;
}
x += velX;
repaint();
if (x < 10 || x > 1200) {
velX = -velX;
repaint();
}
}
public void space() {
velX = 0;
repaint();
}
public void space2() {
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_SPACE) {
space();
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_SPACE) {
space2();
}
}
}
答案 0 :(得分:0)
有多个问题......
使用键绑定代替?见How to use key bindings