I am attempting to write a simple game and whenever I run my code this error apears:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at GameController.paint(GameController.java:41)
It still runs and displays the green rectangle, but paint
runs before initObj
and paint
runs again after InitObj
.
public class GameController extends JFrame{
Land land;
int counter;
ArrayList<Land> Lands = new ArrayList<>();
public GameController(){
initGUI();
}
public void initGUI(){
System.out.println("GUI");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(1000,1000);
initObj();
}
public void initObj(){
System.out.println("Obj");
Lands.add(new Land(this,0,0,this.getSize().width, this.getSize().height));
}
public void step(){
}
public void paint(Graphics g){
System.out.println("paint");
g.setColor(new Color(25,150,50));
g.fillRect(Lands.get(0).xPos,Lands.get(0).yPos, Lands.get(0).Width, Lands.get(0).Height);
}
}
Since paint
is being called before initObj
, why don't you check to see if Lands
has anything in it before trying to access it?
public void paint(Graphics g){
System.out.println("paint");
if (Lands.size() > 0) {
g.setColor(new Color(25,150,50));
g.fillRect(Lands.get(0).xPos,Lands.get(0).yPos, Lands.get(0).Width, Lands.get(0).Height);
}
}
You have created
ArrayList<Land> Lands = new ArrayList<>();
If you did not populate the Lands
object and try to access, you will definitely get IndexOutOfBounds
exception.
Your current code should be modified :
public void paint(Graphics g){
System.out.println("paint");
g.setColor(new Color(25,150,50));
g.fillRect(Lands.get(0).xPos,Lands.get(0).yPos, Lands.get(0).Width, Lands.get(0).Height);
}
Currently you are looking for 0th element. But in future, it may be any index position.
The generic code would be like this:
public void paint(Graphics g){
System.out.println("paint");
g.setColor(new Color(25,150,50));
Land land = null;
try{
land = Lands.get(index); // for your index is 0;
}catch(Exception err){
err.printStackTrace();
}
if ( land != null) {
g.fillRect(land.xPos,land.yPos, land.Width, land.Height);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.