2015-12-23 139 views
2

我想使跟蹤鼠標移動和顯示鼠標當前點到標籤的程序,但是當我運行我的代碼,它給了我沒有在一個JLabel跟蹤鼠標移動

代碼我使用的是:

public class pr1 extends JFrame implements MouseMotionListener 
{ 
    String Name; 
    JLabel PositionLabel; 
    Container cp; 
    float XPosition; 
    float YPosition; 
    Point Point; 

    public pr1 (String Name) 
    { 
    super (Name); 
    setLayout(new FlowLayout()); 
    setBackground(Color.LIGHT_GRAY); 
    setSize(500, 500); 
    setVisible(true); 
    setResizable(false); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 

    PositionLabel = new JLabel ("The mouse now at the point : "); 
    cp = getContentPane(); 
    cp.add (PositionLabel, BorderLayout.SOUTH); 
    } 

    @Override 
    public void mouseMoved(MouseEvent e) 
    { 
    Point = e.getPoint(); 
    PositionLabel.setText("The mouse now at the point : " + Point); 
    } 

    @Override 
    public void mouseDragged(MouseEvent e) 
    { 
    throw new UnsupportedOperationException("Not supported yet."); 
    } 
} 

回答

0

我有同樣的問題在一天:

addMouseMotionListener(this); 

你可以看到一個例子。利用方法myComponent.getMousePosition()來獲取鼠標的位置(在你的情況下,你可能想要添加一個JPanel到框架,然後添加你的JLabel到面板。)。

您可以使用方法與定時器:

Timer t = new Timer(1, e->{ 
    if(myPanel.getMousePosition() != null) 
     myLable.setText("The mouse now at point: " + myPanel.getMousePosition().getX() + ", " + myPanel.getMousePosition().getY()); 
}); 
t.start(); 

注意到,如果鼠標是不是在組件上,getMousePosition()將返回null

+0

Leet_Falcon的回答與我合作,嘗試一下。這比將JPanel添加到框架並使用定時器要容易得多:) –