简体   繁体   中英

JMapViewer: strange behavior of setMovementMouseButton() method

I am trying to change the mouse button to pan the map view from the right button to left.

There is a simple code changing the button after the left mouse button has been clicked:

public class Map extends JMapViewer {

    public Map()         {
            new DefaultMapController(this){
                    public void mousePressed(MouseEvent e) {                   
                            this.setMovementMouseButton(MouseEvent.BUTTON1);
                    }   
            };
    }
}

Main class:

public class JMapViewerDemo {
    public static void main(String[] args) {
           JFrame f = new JFrame();
           f.add(new Map());
           f.setSize(800, 600);
           f.setVisible(true);          
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Surprisingly, the code does not work (no reassignment has been done). Why? However, after calling the parent class method

public void mousePressed(MouseEvent e) {    
     super.mousePressed(e);      //Calling the parent-class method          
     this.setMovementMouseButton(MouseEvent.BUTTON1);
}   

the following behavior was observed:

  1. Click the left mouse button. When dragging no reassignment has been done (the same situation).

  2. Release the left mouse button.

  3. Click the left mouse button again. When dragging, the panning is assign to the left mouse button.

I find this behavior strange. Maybe, I am using this method incorrectly...

How to change the panning button directly, without being released and clicked again? Thanks for your help...

The results seen are not unexpected, but they may be a little counter-intuitive: Your example alters the internal state of the DefaultMapController in your implementation of mousePressed() . Instead, save a reference to the custom controller so that you can change the preferred button as desired:

    JMapViewer map = new JMapViewer();
    DefaultMapController dmc = new DefaultMapController(map){…};
    dmc.setMovementMouseButton(MouseEvent.BUTTON1);

In a desktop application, you might let the user select a preferred mouse button using radio buttons and save the chosen value among the user's Preferences as shown here . Also consider overriding getPreferredSize() , as shown here , instead of invoking setSize() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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