2011-11-18 32 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,沒有在鼠標事件發生

相關問題