【问题标题】:Using Observer pattern to move labels (JavaFx)使用观察者模式移动标签 (JavaFx)
【发布时间】:2012-12-16 01:46:46
【问题描述】:

我正在创建一个聊天程序,其中我的聊天人员是一个标签。当用户点击anchorpane 时,标签可以在屏幕上移动,现在这里有两个senerios:

  1. 聊天者必须在本地移动。

  2. 客户端必须将此移动发送给所有其他连接的客户端。

如果对象可以正常工作,则第二种情况很容易,目前我的 ChatPerson 对象如下所示:

 package GUI;


public class ChatPerson {

    private String username;
    private int x;
    private int y;
    // Brugerens ID i databasen
    private int id;

    public ChatPerson(String name){
        this.username = name;
    }

    public String getUserName(){
        return username;
    }
    public void setX(int x){
        this.x = x;
    }
    public void setY(int y){
        this.y = y;
    }
    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
    public int getId(){
        return id;
    }
    public void setId(int id){
        this.id = id;
    }



}

我的问题是我将如何实现这种行为。我查找了观察者模式,但我发现在这种情况下如何让它发挥作用很难?

另外,JavaFx 是否有某种我可以在这里使用的实现?我看过 Observablelist,但我真的不明白这对我有什么帮助?

【问题讨论】:

    标签: java javafx observer-pattern


    【解决方案1】:

    在这种情况下,您可以使用观察者模式。我假设您在每个客户的某个地方都有一个相关人员列表。如果这是一些,通知其他人移动事件应该很简单。只需像这样使 ChatPerson 可观察

    public class ChatPerson {
         //your props here :P...
        private final List<MoveListener> listeners = new ArrayList<MoveListener>();
    
        private void notifyListeners(MoveEvent e){
            for(MoveListener l : listeners){
                 l.onMoveEvent(e);
            }
        }
        public void addMoveListener(MoveListener l){
            this.listeners.add(l);
        }
        public void removeMoveListener(MoveListener l){
            this.listeners.remove(l);
        }
    
        //i would create a move method but you can do this on setX() and setY()
        public void move(int x,int y){
            this.x=x;
            this.y=y;
            this.notifyListeners(new MoveEvent(this,x,y));
        }
        //your other method...
    }
    

    现在是 MoveListener 接口。

    public interface MoveListener{
        public void onMoveEvent(MoveEvent e);
    }
    

    还有 MoveEvent。

    public class MoveEvent{
        public final ChatPerson source;//i could be more generic but you get the ideea
        public final int currentX;
        public final int currentY;
        public MoveEvent(ChatPerson source, int x,int y){
            this.source = source;
            this.currentX = x;
            this.currentY = y;
        }
        //you can make the fields private and getters ofc :P
    }
    

    现在,每当 ChatPerson 移动时,它都会以一种很好且通用的方式广播其位置,这取决于每个听众对其内容的响应以响应此事件。
    在容器类(具有关联人员列表的类)中,只需实现一个 MoveListener 并将其添加到当前 ChatPerson。
    在这个实现中,您可以遍历连接的人员列表并可以说“通过电线”发送当前位置。如果没有更多关于如何实现您的应用的详细信息,我真的无法给出更好的答案。
    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-20
      • 2023-04-10
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 2013-03-05
      • 2016-05-11
      • 1970-01-01
      相关资源
      最近更新 更多