我正在将自己作为Java的俄罗斯方块克隆,作为一个学习项目。但是,我现在停留在获取用于左右移动乐曲的输入的部分。我不确定问题出在我的方法中,还是在keyPressed方法未被调用中,我没有成功调试,因为它忽略了该方法。这是我的代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
public class MainClass implements KeyListener{
public static Painter painter = new Painter();
public static LShape tetr = new LShape(150,0);
public static void main(String[] args) throws InterruptedException {
JFrame window = new JFrame("Tetris");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300, 560);
window.setBackground(Color.BLUE);
window.getContentPane().add(painter);
window.setVisible(true);
ArrayList<Block> blocks = new ArrayList<Block>();
ArrayList<Block> staticBlocks = new ArrayList<Block>();
while(true){
tetr = new LShape(150, 0);
for (int i = 0; i < tetr.iterations; i++) {
blocks = new ArrayList<Block>(Arrays.asList(tetr.getBlocks()));
blocks.addAll(staticBlocks);
painter.setBlocks(blocks);
tetr.changeY(5);
Thread.sleep(35);
painter.repaint();
}
staticBlocks.addAll(blocks);
}
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) { //I am not sure if this is even called
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:
tetr.changeX(20);
break;
case KeyEvent.VK_LEFT:
tetr.changeX(-20);
}
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
最佳答案
MainClass
不在任何地方使用。
创建一个实例,并将keylistener添加到窗口对象(JFrame实例)中,该侦听器在您的代码中为MainClass。
使用这个window.addKeyListener(new MainClass());
public class MainClass implements KeyListener {
public static Painter painter = new Painter();
public static LShape tetr = new LShape(150, 0);
public static void main(String[] args) throws InterruptedException {
JFrame window = new JFrame("Tetris");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300, 560);
window.setBackground(Color.BLUE);
window.addKeyListener(new MainClass());
// window.getContentPane().add((PopupMenu) painter);
window.setVisible(true);
ArrayList<Block> blocks = new ArrayList<Block>();
ArrayList<Block> staticBlocks = new ArrayList<Block>();
while (true) {
tetr = new LShape(150, 0);
for (int i = 0; i < tetr.iterations; i++) {
blocks = new ArrayList<Block>(Arrays.asList(tetr.getBlocks()));
blocks.addAll(staticBlocks);
painter.setBlocks(blocks);
tetr.changeY(5);
Thread.sleep(35);
painter.repaint();
}
staticBlocks.addAll(blocks);
}
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) { //I am not sure if this is even called
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
// tetr.changeX(20);
break;
case KeyEvent.VK_LEFT:
// tetr.changeX(-20);
}
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}