Java 使用 bookClasses SimpleTurtle 的简单绘图程序

Java simple drawing program using bookClasses SimpleTurtle

对于我的在线 Java class 我一直在尝试让一个简单的绘图程序工作。我正在使用 bookClasses (to run the program you need this library) to make a world object with a turtle in it. To draw, I've been using a mouselistener. My problem is that I have two windows: one that I draw on, the other that the lines show up on. I would like to draw on the same window the lines are creates on. Here 是我正在使用的乌龟的文档。 (我在这里只使用继承自 SimpleTurtle 的 Turtle)。不管怎样,这是我的代码:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

class MyMouseAdapter extends MouseAdapter {
   World worldObj = new World();
   Turtle turtle = new Turtle(1000, 1000, worldObj);

    public void mousePressed(MouseEvent e) {
        int xPressed = e.getX();
        int yPressed = e.getY();
        System.out.printf("Mouse Clicked at: %d, %d%n", xPressed, yPressed);
        turtle.hide();
        turtle.penUp();
        turtle.moveTo(xPressed, yPressed);
   }
   public void mouseReleased(MouseEvent e) {
       int xReleased = e.getX();
       int yReleased = e.getY();
       System.out.printf("Mouse Released at: %d, %d%n", xReleased, yReleased);
       turtle.show();
       turtle.penDown();
       turtle.moveTo(xReleased, yReleased);
       turtle.hide();
   }
}

public class WorldTest2 {   
   public WorldTest2() {
       World worldObj = new World();
       worldObj.addMouseListener(new MyMouseAdapter());
   }

   public static void main(String[] args) {
       WorldTest2 test = new WorldTest2();
   }   
}

我知道为什么它不起作用(我在一个世界上创建海龟,但在另一个世界上创建鼠标侦听器),但我不知道如何修复它。有帮助吗?

在你的 WorldTest 2 class 添加一个 getter() 方法

public class WorldTest2{
      World worldObj;
      public World(){
           worldObj = new World();
       }
       public World getWorld(){ //Now call this in MyMouseAdapter Class 
           return worldObj;         // instead of creating new Object of World
       }
 }

MyMouseAdapterclass

class MyMouseAdapter extends MouseAdapter {
   World worldObj = new WorldTest2().getWorld();
}

好吧,我以为我什么都试过了,但我想我错了!一边琢磨一边想出了解决办法。

我刚改了

   public WorldTest2() {
   World worldObj = new World();
   worldObj.addMouseListener(new MyMouseAdapter());
   }

   public WorldTest2() {
   MyMouseAdapter draw = new MyMouseAdapter();
   draw.worldObj.addMouseListener(draw);
   }

而且效果很好!