-1
我正在尝试制作基于拼贴的游戏。我做了一个Tile
课程,并给每个课程自己的Rectangle
进行碰撞。一旦我呈现并更新它们,我将它们全部存储到ArrayList
中。这部分工作正常,但是当我尝试通过getter访问来自另一个类的相同ArrayList
时,我得不到任何元素。我检查我的控制台大小,它给了我正确的号码,但是当我尝试实际获得元素 即rect.get(0)
,我得到这些错误:需要与ArrayList同步的帮助
Exception in thread "Thread-3" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
我认为这是一个线程安全性问题,但我已经尝试了所有我能想到的使用synchronize
关键字Collections
,但没有运气。任何帮助将非常感激。
用代码编辑。关于不张贴早些时候
public class Launcher extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 1500;
private static final int HEIGHT = 900;
private static final String title = ("Game Alpha");
volatile boolean running;
Thread CT;
Canvas canvas = new Canvas();
Dimension size = new Dimension(WIDTH, HEIGHT);
Camera camera;
Controls controls;
PlayerTest pt;
BufferStrategy BS;
Graphics graphics;
//I'm declaring the arrayList here
public ArrayList<Rectangle> bounded = new ArrayList<Rectangle>();
public Launcher() {
Sprites.resources();
controls = new Controls();
GUI();
//The camera class is the one in which I'm trying to access the list
//It's there right now just to test, I plan on changing it later
camera = new Camera(this, controls, 0, 0);
pt = new PlayerTest(this, canvas.getWidth()/2, canvas.getHeight()/2);
Tiles.tileSets();
CT = new Thread(this);
START();
}
public void GUI() {
setTitle(title);
setPreferredSize(size);
setResizable(false);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addKeyListener(controls);
canvas.setPreferredSize(size);
canvas.setMaximumSize(size);
canvas.setMinimumSize(size);
canvas.setFocusable(false);
add(canvas);
setVisible(true);
}
public void render() {
BS = canvas.getBufferStrategy();
if(BS == null) {
canvas.createBufferStrategy(3);
return;
}
graphics = BS.getDrawGraphics();
graphics.setColor(Color.ORANGE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
Rectangle cam = new Rectangle((int)camera.getX(),
(int)camera.getY(),
camera.getWidth(),
camera.getHeight());
//Here I'm looping to get my tiles
for(int x = 0; x < 64; x++) {
for(int y = 0; y < 64; y++) {
Tiles.getTile(LevelCode.code[y][x]).setBounds(x * 50 - (int)camera.getXof(), y * 50 - (int)camera.getYof());
//Here I'm adding the rectangles from each tile into the array
bounded.add(new Rectangle(Tiles.getTile(code[y][x]).getBounds()));
}
}
pt.render(graphics);
BS.show();
graphics.dispose();
//Here after I render the tiles I clear the list, for my updates, then //repopulate
bounded.clear();
}
public ArrayList<Rectangle> getList() {
return bounded;
}
}
我们不能调试我们看不到的代码。请构建一个可测试的最小示例。阅读http://stackoverflow.com/help/mcve –
我认为这是一个多线程问题的设计问题。您可以使用关键字“synchronized”使线程保存方法。所以请插入一些代码示例。 – Petterson
我打赌100个SO点,他有2个名单,他试图阅读的是空的。 – Kayaman