I have a mini project for java to do and I have some setbacks.
I want to pass the value of a keypress to my main class in order to call some methods that will move a certain value up,down,left or right inside a matrix, and then if possible paint a GUI based of the values inside that matrix.
Here is my class that returns the key code of the key I press inside a 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;}
}
My main class where I create and want to modify the matrix is this.
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;}
}
}
}
Any idea how I can do this ? Is there any example of a program that resembles mine?
Thanks for the help and guidance!