【发布时间】:2015-01-21 01:22:30
【问题描述】:
为什么arraylist.get(0)运行时会报错。编译时我没有收到错误,但是当我运行它时,它运行得很好,但它给出了:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
并且程序报告错误在实现arraylist.get(0) 的行中。我在paint() 外部声明了arraylist,它给出了上面的错误。但是当我在paint() 中声明它时,没有报错。但是,我想在外面声明arraylist。
如何在 paint(); 外部声明 arraylist?
下面是我的代码:
class Game{
int x=0, y=250;
String line;
String[] list;
static ArrayList<String> arraylist;
public static void main(String[] args){
Game game= new Game();
game.read();
}
public void read(){
arraylist= new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
line= br.readLine();
list= line.split(" ");
for(int i=0; i<list.length ;i++)
arraylist.add(list[i]);
Collections.shuffle(arraylist);
}
catch(Exception e){}
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2= (Graphics2D)g;
Font font= new Font("Impact",Font.PLAIN,10);
g2.setFont(font);
g2.drawString(arraylist.get(0),x,y);
try{
Thread.sleep(50);
}
catch(Exception e){}
repaint();
}
}
更新:修改了代码
【问题讨论】:
-
你的列表是空的。也许您可以向我们展示您如何尝试填充它。另外,
Thread.sleep(50);...repaint();不要在油漆内这样做!!!使用计时器。 docs.oracle.com/javase/tutorial/uiswing/misc/timer.html -
能否提供
decripted.txt文件的内容? -
@atishshimpi 内容无关紧要。它只包含用空格分隔的单词。解析时逐字逐句获取
-
是的,我已经尝试使用示例文件,其内容由您的代码中的空格分隔,并且工作正常。
-
静态化并不是正确的解决方案。注意 你不能在paint() 方法中睡觉。您需要使用
SwingTimer来安排您的重绘。