2011-11-18 33 views
1

我正在创建地图编辑器,并且他们点击的地方将用于将数据点添加到地图。为什么每次点击时java MouseListener都会返回相同的值x和y值?

public MapEditor() throws HeadlessException, FileNotFoundException, XMLStreamException { 
    super("MapEditor"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    // Set JFrame properties. 
    this.setTitle("Map Editor"); 
    this.setSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); 
    this.setBackground(Color.gray); 

    this.setJMenuBar(makeMenuBar()); 

    JPanel mainPanel = new JPanel(new BorderLayout()); 

    Icon image = new ImageIcon("map.jpg"); 
    JLabel label = new JLabel(image); 
    scrollPane = new JScrollPane(); 
    scrollPane.getViewport().add(label); 

    scrollPane.addMouseListener(this); 

    mainPanel.add(scrollPane, BorderLayout.CENTER); 


    this.getContentPane().add(mainPanel); 

    this.getContentPane().add(makeStatusBar(), BorderLayout.SOUTH); 

    setVisible(true); 
} 

我也有被点击鼠标时以下事件:

public void mouseClicked(MouseEvent e) { 
    int x = getX(); 
    int y = getY(); 
    System.out.println("clicked at (" + x + ", " + y + ")"); 
} 

但是,无论身在何处我在窗口中单击,它返回相同的值。我注意到,如果我将整个窗口移动到屏幕上的其他位置,它会返回不同的值。它们看起来与窗口的左上角相对应。我已经尝试将MouseListener添加到不同的组件,但是我获得了每个组件的相同结果。一些帮助将不胜感激。

+0

里面是什么的getX和方法的getY? – r0ast3d

回答

5

改为使用MouseAdapter,因为它是用于接收鼠标事件的抽象适配器类。

有关代码示例,请参阅Java MouseListener的接受答案。

编辑:您没有使用MouseEvent变量引用,以便getX()getY()不会返回你所期望的,除非getX()getY()是你自己的方法?

你的代码更改为:

public void mouseClicked(MouseEvent e) { 
    int x = e.getX(); 
    int y = e.getY(); 
    System.out.println("clicked at (" + x + ", " + y + ")"); 
} 
+0

+1好抓:-) – kleopatra

0

想通了。它需要:

public void mouseClicked(MouseEvent e) { 
    int x = e.getX(); 
    int y = e.getY(); 
    System.out.println("clicked at (" + x + ", " + y + ")"); 
} 

之前,我刚开窗格中的X和Y,没有在鼠标事件发生

相关问题