我有一个java项目的迷你项目,我有一些挫折。
我想将按键的值传递给我的主类,以便调用一些方法,这些方法会在矩阵内上下左右移动某个值,然后根据值绘制GUI在那个矩阵里面。
这是我的类,它返回我在GUI中按下的键的键代码。
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Keys extends JFrame implements KeyListener{
public static int keyVALUE;//I want to use this value inside another class
public Keys()
{
addKeyListener( this );
}
public void keyReleased(KeyEvent e) {
displayInfo(e);
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
private int displayInfo(KeyEvent e){
int id = e.getID();
if (id == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
} else {
keyVALUE = e.getKeyCode();
System.out.print(keyVALUE);
}
return keyVALUE;}
}
我创建并想要修改矩阵的主要类是这个。
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Matrix extends Keys {
public static int[][] Matrix = new int[9][9];
public void moveUp(){
}
public void moveDown(){
}
public void moveLeft(){
}
public void moveRight(){
}
public static void main(String[] args)
{
//since there is no GUI, here is a frame that picks up the key releases
Keys keyPressed = new Keys();
keyPressed.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
keyPressed.setSize( 800, 600 ); // set frame size
keyPressed.setVisible( true); // display frame
//set "car "2" and blocks "1" and paint GUI based on this
for (int i = 0; i <9; i++) {
for (int j = 0; j < 9; j++) {
Matrix[i][j] = 0ș
Matrix[4][4]=2;//start position
System.out.print(Matrix[i][j] + " ");
}
System.out.println();
}
for(;;){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
for (int i = 0; i <9; i++) {
for (int j = 0; j < 9; j++) {
if(Matrix[i][j]==2 && Matrix[i-1][j]==0){
Matrix[i-1][j]=2;
Matrix[i][j]=0;
Matrix[i][j]=Matrix[i-1][j];
Matrix[i-1][j]=2;
Matrix[i][j]=0;
}}}
for (int i = 0; i <9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(Matrix[i][j] + " ");
}
System.out.println();
}
if(Matrix[0][4]==2){JOptionPane.showMessageDialog(null,"You WON!","Winner",JOptionPane.INFORMATION_MESSAGE);break;}
if(Matrix[0][8]==2){break;}
}
}
}
知道我怎么能这样做吗? 有没有类似我的程序的例子?
感谢您的帮助和指导!