Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);

    }
}
share|improve this question
    
Your question is not well presented. You should mention that your problem is compile-time and provide the error messages, even if in your case it is possible to answer just with the code –  Dici 15 hours ago
    
you simply say int[x] or whatever index = what you want to put in it ie currentkeys[0] = e.getKeyCode, however you need to specify the size of the array before you use it –  David Coler 15 hours ago

4 Answers 4

up vote 1 down vote accepted

Try replacing int currentKeys[] = {}; with ArrayList<Integer> currentKeys = new ArrayList<Integer>();


Explanation: Arrays in Java are fixed-size data structures. This means you can't add elements to an array because that would be changing the size of the array. You can set the value of a position in an array using the code:

currentKeys[index] = newValue;

But this of course can't ever change the total size of the array. Furthermore, by initializing currentKeys with:

int[] currentKeys = {};

You're creating a length 0 array, so it will never be able to hold anything.

If you know exactly how many elements currentKeys will ever have in it, an array is appropriate. From your question it even seems that the answer may be 2, in which case you could use

int[] currentKeys = new int[2];

If, however, you don't know the ultimate size of currentKeys or require it to dynamically resize throughout your operations, then an array is not sufficient.

An ArrayList is a dynamically sized datastructure that functions as an array. Unlike an array, you can add an element to an ArrayList, effectively increasing its size by 1. (You can also remove elements, decreasing the size). Like an array, you can also get the value at an index or set the value at a given index, provided those indices are in bounds.

ArrayList<Integer> currentKeys = new ArrayList<Integer>(); //Create an empty arraylist
currentKeys.add(2); //Add 2 to the back of the arraylist. Now [2].
currentKeys.add(3); //Add 3 to the back of the arraylist. Now [2, 3].
int first = currentKeys.get(0); //Gets the value at index 0 (0 being the first position), -> 2
currentKeys.set(1, 5); //Sets the value at index 1 to 5. Now [2, 5].
share|improve this answer

currentKeys is int[] and it doesn't have add() method, ArrayList is what you are looking for

share|improve this answer
    
Is there an alternative method I can use to add items to an int[] array? –  RecentWebDev2000 15 hours ago
1  
Use List<Integer> currentKeys = new ArrayList<>(); and then use currentKeys.add(someIntNum) –  Jigar Joshi 15 hours ago
1  
@RecentWebDev2000 if you don't want to get frustrated with Java, learn it. Arrays are a basic component every developer should know how to use in any language –  Dici 15 hours ago

Arrays don't have an add() (or remove()) method defined. You're looking for a List implementation (LinkedList, ArrayList, etc).

For completeness, the way one adds elements into an array is by indexing into it. This requires that you know the current position that you're adding into (so you don't overwrite other data), and how large the array is (to avoid stepping out of it).

That could be done via this:

currentKeys[currentIndex++] = c;

If you were looking to do that with this array, though...

int currentKeys[] = {};

...that'd be impossible, since it's an array of size 0 - and you cannot index into an array of size 0. Arrays don't dynamically grow; they're fixed in size.

share|improve this answer

Arrays in Java are simply multiple objects in an array that can be iterated. The are accessed via index currentKeys[index] and does not provide any methods for editing the array.

What you are looking for is something that is index based but has methods for dynamically adding and removing data.

The java.util.List interface provides that for you (JavaDoc). There are multiple List-implementations but one of them is the java.util.ArrayList.

So, to use the list the following can be of inspiration:

List<Integer> currentKeys = new ArrayList<>(); // Declare and initialize a List of type ArrayList
currentKeys.add(123); // add a value
currentKeys.remove(Integer.valueOf(123)); // remove the key 123
currentKeys.add(111); // add a value
currentKeys.remove(0); // remove the first entry in the list

Note that a List of Integers can be tricky. If you pass an int to the remove method the int defines which index to be removed. If you pass an Integer to the method you match the actual object to remove as in the code sample above.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.