2011-11-08 335 views
2
public class mouse extends JFrame { 
    private int x, y; 
    private JLabel label; 

    public mouse() { 
     JPanel panel = new JPanel(); 
     addMouseMotionListener(new MouseMotion()); 
     label = new JLabel(); 
     panel.add(label); 
     setPreferredSize(new Dimension(400, 200)); 
     add(panel, BorderLayout.SOUTH); 
     pack(); 
     setVisible(true); 
    } 
    private class MouseMotion extends MouseMotionAdapter { 
     public void mouseMoved(MouseEvent e) { 
      x = e.getX(); 
      y = e.getY(); 
      label.setText("mouse coordinate " + "(" + x + "," + y + ")"); 
    }} 
    public static void main(String[]args) { 
     mouse a = new mouse(); 
    } 
} 

當我將鼠標移動到邊界時,它不是(0,0)。爲什麼?例如,我將鼠標移動到左上角,它顯示(4,30)而不是(0,0)。鼠標的座標?

回答

5

將MouseListener或MouseMotionListener添加到JFrame的contentPane,而不是JFrame本身,否則您不得不擔心邊框,菜單,插圖等等。例如:

getContentPane().addMouseMotionListener(new MouseMotion()); 

此外,請格式化您的代碼,以便我們可以閱讀它。