简体   繁体   English

另一个类中的链表可以通过一种方法访问但不能通过另一种方法访问

[英]A linked list in another class accessible from one method but not from another

Ok I'm really not understanding why this isn't working.好吧,我真的不明白为什么这不起作用。

class SketcherModel extends Observable implements Iterable<Element>{

    public Iterator<Element> iterator(){
        return elements.iterator();
    }   

    public LinkedList<Element> elements = new LinkedList<Element>();
}

So I have a LinkedList in the class Element in the 'model' portion of my application.所以我在我的应用程序的“模型”部分的类Element中有一个 LinkedList。 The idea is that when the 'view' portion of the app executes the paint() method it'll access the linked list and draw each Element it contains, as shown in the code below:这个想法是,当应用程序的“视图”部分执行paint()方法时,它将访问链表并绘制它包含的每个Element ,如下面的代码所示:

public class SketcherView extends JComponent implements Observer{
    public SketcherView(Sketcher theApp){
        this.theApp = theApp;

        //Testing to see if I can access the linked list, 'elements', outside of the paint() method;
        Element test = theApp.getModel().elements.iterator().next() 
    }

    public void update(Observable o, Object rectangle){
        //Code to respond to changes in model...
    }

    public void paint(Graphics g){
        Graphics2D g2D = (Graphics2D)g;
        for(Element element : theApp.getModel()){
            element = (Element)elements.iterator().next();
            g2D.setPaint(element.getColor());
            g2D.draw(element.getShape());
        }    
    } 

Now when accessing the linked list elements from the class constructor it seems to find it with no problems , however when I used the collection-based for loop to run through elements using the iterator it says 'elements cannot be resolved'.现在,当从类构造函数访问链表elements ,它似乎没有问题,但是当我使用基于集合的 for 循环使用迭代器运行elements ,它说“元素无法解析”。 Am I missing something?我错过了什么吗?

public void paint(Graphics g){
    Graphics2D g2D = (Graphics2D)g;
    for(Element element : theApp.getModel()){
        element = (Element)elements.iterator().next();
        g2D.setPaint(element.getColor());
        g2D.draw(element.getShape());
    } 
}

You don't have any elements variable in the method.方法中没有任何elements变量。 And the current element of the loop is already declared in the for loop.并且循环的当前元素已经在 for 循环中声明。 The code should be代码应该是

for(Element element : theApp.getModel()){
    g2D.setPaint(element.getColor());
    g2D.draw(element.getShape());
} 

Another, unrealated problem, is that you should override paintComponent() , and not paint() .另一个未实现的问题是您应该覆盖paintComponent() ,而不是paint()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM