问题与链接列表(Java小程序) [英] Issue with Linked List (Java applet)

查看:140
本文介绍了问题与链接列表(Java小程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此code,我试图初始化发送到一个类要绘制椭圆的链接列表。

In this code, I am trying to initialize a linked list of ovals that are sent to a class to be drawn.

public void actionPerformed(ActionEvent e)
  {
    oval p;
    Graphics g = this.getGraphics();
    int x, y, height, width, fill;
    ListIterator li;
    LinkedList<oval> list = new LinkedList<oval>();
    li = list.listIterator();
    x = Integer.parseInt(xfield.getText());
    y = Integer.parseInt(yfield.getText());
    height = Integer.parseInt(heightf.getText());
    width = Integer.parseInt(widthf.getText());
    list.add(new oval(x,y,height,width));
    repaint();
    while (li.hasNext()) 
    {
        p = (oval)li.next();
        p.draw(g);
    }

当我运行它,我得到这个异​​常:

When I run this, I get this exception:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
    at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
    at java.util.LinkedList$ListItr.next(Unknown Source)
    at ovalapplet.actionPerformed(ovalapplet.java:97)

我该如何解决这个问题? (97号线为p =(椭圆形)li.next();是否有帮助)

How can I fix this? (Line 97 is p = (oval)li.next(); if that helps.)

推荐答案

您获取列表的迭代器的之前您更改列表的状态,然后使用迭代器遍历,但现在迭代器已不再适合。解决方法:更改顺序。获取后只迭代器的 将项目添加到列表中,或使用的ListIterator并用的ListIterator添加项目。

You get the list's iterator before you change the state of the list, and then you use the iterator to iterate through, but now the iterator is no longer appropriate. Solution: change that order. Get the iterator only after adding items to the list, or use a ListIterator and add items with the ListIterator.

其他问题:您正在绘制错误,你不应该调用的getGraphics()的组件上,因为这会返回一个短暂的对象获取一个Graphics对象。要明白我的意思,一旦你得到你的GUI的工作,最大限度地减少,然后做这个图纸后恢复,看你的图纸消失。而是使用一个LinkedList的领域,改变你的actionPerformed方法的状态,叫重绘()和你的组件的的paintComponent(图形G)方法(或涂料(图形G),如果这是一个AWT程序法)为你做绘图。

Other problems: you're drawing incorrectly as you should not get a Graphics object by calling getGraphics() on a component as this returns a short-lived object. To see what I mean, once you get your GUI working, minimize and then restore it after doing this drawing and watch your drawings disappear. Instead use a LinkedList field, change its state in your actionPerformed method, call repaint() and have your component's paintComponent(Graphics g) method (or the paint(Graphics g) method if this is an AWT program) do the drawing for you.

这篇关于问题与链接列表(Java小程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆