开发者

Respond to events in other JPanels

Ok so lets say I have 3 Jpanels - 1 parent and 2 Children

//开发者_高级运维Assume necessary imports etc

parent is something like:

public class ParentPanel extends JFrame  {
private JPanel mainPanel,controlPanel;

public ParentPanel(){
    MainPanel pp= new ParentPanel();
    controlPanel cp = new controlPanel();
}
...

Main Panel in real thing is like a 2d graphics thing but not important for the point so simplified:

public class MainPanel implements MouseMotionListener{
    public MainPanel(){
        //not important now 
    }

    public void MouseMoved(MouseEvent arg0){
        int xPos e.getX
    }
...

What i want to do is get the X pos of the mouse and pass it from main panel up to the parent and into a label for example on the sibling control panel.

Any ideas clues or pointers appreciated thanks


Depending on how complicated the GUI is you can pass the ParentPanel object as a parameter to the MainPanel object. In the MainPanel you have access to all the ParentPanel's components etc.

 public class MainPanel implements MouseMotionListener{

 ParentPanel parent;

 public MainPanel(ParentPanel p){
    //not important now
    parent = p; 
 }

 public void MouseMoved(MouseEvent arg0){
    //Access to parent here.
 }

And in the ParentPanel when you create teh MainPanel:

MainPanel pp= new MainPanel(this);

This is of course a very simple solution and more complicated GUIs will not be suitable.


You could write a pass-through listener. Something in the child panel that the parent can listen too. Then when the child received a mouse moved event it would broadcast it back up to the parent.

You could also make the label on the sibling control panel into a small model object. Then both of the children listeners would know about the model object. One child would modify it and the other would listen for updates.


You could create an interface that is notified of the changes which ParentPanel can then implement and MainPanel can use to pass the message along.

interface XPositionListener {
    void updateXPosition(int xPos);
}  

public class ParentPanel extends JFrame implements XPositionListener  {
    private MainPanel mainPanel; private ControlPanel controlPanel;

    public ParentPanel() {
        mainPanel = new MainPanel(this);
        controlPanel = new ControlPanel();
    }

    void updateXPosition(int xPos) {
        // Update a label or whatever
    }   

    // ...
}

public class MainPanel implements MouseMotionListener {
    XPositionListener listener;

    public MainPanel(XPositionListener listener) {
         this.listener = listener;
    }

    public void MouseMoved(MouseEvent event) {
        int xPos = event.getPoint().x;
        listener.updateXPosition(xPos);
    }

    // ...
}

Check out the Observer Pattern for information on a more robust solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜