Java小程序在窗口中心显示文本在开始时和鼠标移动时跟随

时间:2014-12-01 01:18:26

标签: java applet mousemotionlistener

我正在尝试编写一个程序,在启动时显示一个字符串,然后一旦鼠标移动到窗口中它跟随它,然后一旦鼠标退出窗口就停止。我能够让String跟随鼠标,但似乎无法让它在程序启动时显示中心并跟随鼠标。我尝试使用更新,但只是立即绘制了几个String。任何指导表示赞赏。

这是我的代码。

import java.awt.*;
import java.applet.*;
import javax.awt.event.*;

public class Follow_Me extends Applet implements MouseListener, MouseMotionListener{
        int x;
        int y;
        String text;

   public void init(){
       // Add Mouse Listeners
       addMouseListener(this);
       addMouseMotionListener(this);

   }

   public void paint(Graphics g){
     /* This is where I want to display the String
        and then allow it to move wherever the mouse moves 
        once inside window. 

        g.drawString("Hello", 230, 150);

        but once I set it to the center, my mouseMoved
        will not do anything. It will only move with
        text if the coordinates are set within method.

     */

     g.drawString("Hello", x,y);
   }

   // Unused mouse listeners
   public void mouseReleased (MouseEvent e){}
   public void mouseClicked (MouseEvent e){} 
   public void mouseDragged (MouseEvent e){}
   public void mousePressed (MouseEvent e){}
   public void mouseEntered (MouseEvent e){}
   public void mouseExited (MouseEvent e){}

   // Used mouse motion listener
   public void mouseMoved (MouseEvent e){
        x = e.getX();
        y = e.getY();
        text = "Hello";
        repaint();
   }

0 个答案:

没有答案