有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用RMI移动多个球时出现java问题?

我正在使用RMI制作移动球的分布式动画

我的目标是以某种方式移动多个球,以便多个客户端观察球的相同移动/位置,我使用的是ball对象,它是远程对象

当球只有一个时,球移动的很好,但是当我试图增加球的数量时,我失败了

下面是一些代码片段,我在其中应用循环来处理多个球:

在服务器上:

  b[0] = new BallImpl(0, 50, 2, 3 ,Color.YELLOW,20);
  b[1] = new BallImpl(50, 50, 4, 3,Color.BLUE,10);
  b[2] = new BallImpl(40, 40, 5, 5, Color.PINK,30);
  b[3] = new BallImpl(60, 70, 4, 6, Color.GREEN,40);

    for (int i = 0; i < currentNumBalls; i++) {

      Naming.rebind ("rmi://localhost/BouncingBall", b[i]);  // registers Ball object
      System.out.println ("remote ball object registered.");
    }

在客户端站点:

这就是我查找遥控球的方式:

 for (int i = 0; i < currentNumBalls; i++) {
        try {
            this.aBall[i] = (Ball) Naming.lookup("rmi://localhost/BouncingBall");

        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
    start();    

这就是移动球代码:

public void moveballs() {

        for (int i = 0; i < currentNumBalls; i++) {
            try {

                aBall[i].setBounds(pit.getWidth(), pit.getHeight());
                aBall[i].move();

                pit.repaint();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

这就是图纸代码:

 public void drawballs(Graphics g) {

    for (int i = 0; i < currentNumBalls; i++) {
        try {

            g.setColor(aBall[i].getColor());
            g.fillOval(aBall[i].getX(), aBall[i].getY(), aBall[i].getradius(), aBall[i].getradius());

        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }
}

有人能告诉我为什么我只能看到一个球在移动,其他球呢,或者这个设计有问题,我用错了RMI?或者向我推荐一些可以实现目标的设计

非常感谢

吉比


共 (1) 个答案

  1. # 1 楼答案

    看起来你把所有的球都用同一个名字绑起来了。你需要给他们起不同的名字,比如:

    for (int i = 0; i < currentNumBalls; i++) {
    
      Naming.rebind ("rmi://localhost/BouncingBall"+i, b[i]); //add index to the name
      System.out.println ("remote ball object registered.");
    }
    

    然后在查找它们时,使用以下命令:

     for (int i = 0; i < currentNumBalls; i++) {
        try {
            this.aBall[i] = (Ball) Naming.lookup("rmi://localhost/BouncingBall"+i);
    
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }