【问题标题】:Why does the variable declared outside paint() is not recognized inside paint()?为什么在paint() 外部声明的变量在paint() 内部无法识别?
【发布时间】: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 来安排您的重绘。

标签: java swing arraylist


【解决方案1】:

在将任何内容添加到arraylist 之前,会在 UI 线程中多次调用 Paint。 您可以简单地检查它是否不为空,并在其中列出一项。

【讨论】:

  • 好的,哈哈。感谢您的回答,我刚刚运行它,没有错误。我只是将文件阅读器代码放入main(),并将代码的所有变量设为static
  • @yologaming :-) 这样你在 UI Thread 启动之前填充了数组列表,基本上是相同的想法。
猜你喜欢
  • 1970-01-01
  • 2015-02-10
  • 2012-08-27
  • 2012-02-06
  • 2018-01-06
  • 2019-02-08
  • 2011-05-07
  • 1970-01-01
相关资源
最近更新 更多