Update: I apologize for my ignorance everyone. I jumped into this too quickly, and I thought that the type of array I was using could be declared and manipulated later. I thank you all for your informative feedback.
I am a little bit frustrated with Java. I am attempting to independently make a program that animates smooth graphics. In order to do this, I am trying to make a simple square move diagonally when the certain two keys are pressed. I am approaching this challenge by storing the current keys in an array, and adding items to the array when a particular key is pressed. However, it appears that Java is catching two errors: One on line 42, and the other on line 58. I assume this has something to do with the fact I used Array methods on those lines. Could someone please correct me if I am using the wrong array methods, or explain an easier way to accomplish the task I am attempting?
Here is the code:
//Testing some of them graphics
import java.awt.*;
import java.util.Arrays;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.ImageIcon;
public class SmoothAnimations extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this);
int x = 0, velX = 0, y = 0, velY = 0;
int numOfKeys = 0;
int currentKeys[] = {};
public SmoothAnimations(){
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(x,y,100,100);
}
public void actionPerformed(ActionEvent e){
if(x < 0){x = 0;velX = 0;}
if(x > 350){x = 350;velX = 0;}
if(y < 0){y = 0;velY = 0;}
if(y > 350){y = 350;velY = 0;}
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e){
numOfKeys++;
int c = e.getKeyCode();
currentKeys.add(c);
if(numOfKeys == 1){
if(c == KeyEvent.VK_LEFT){velX = -1; velY = 0;}
if(c == KeyEvent.VK_RIGHT){velX = 1; velY = 0;}
if(c == KeyEvent.VK_UP){velX = 0; velY = -1;}
if(c == KeyEvent.VK_DOWN){velX = 0; velY = 1;}
}
//left = 37, up = 38, right = 39, down = 40
if(numOfKeys == 2){
if(c == KeyEvent.VK_LEFT && currentKeys[1] == 38){velX = -1; velY = -1;}
if(c == KeyEvent.VK_LEFT && currentKeys[1] == 40){velX = -1; velY = 1;}
if(c == KeyEvent.VK_RIGHT && currentKeys[1] == 38){velX = 1; velY = -1;}
if(c == KeyEvent.VK_RIGHT && currentKeys[1] == 40){velX = 1; velY = 1;}
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){velX = 0;velY = 0;numOfKeys--;currentKeys.remove(currentKeys.length - 1);}
public static void main(String[] args) {
SmoothAnimations an = new SmoothAnimations();
JFrame jf = new JFrame();
jf.setTitle("Animations Test");
jf.setSize(500,500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(an);
}
}