trymouse.java

来自「Java 入门书的源码」· Java 代码 · 共 56 行

JAVA
56
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Fills a red polygon when the user presses the mouse
 * inside it.  Fills the polygon in blue when the user
 * releases the mouse inside it.  Draws "Got the mouse"
 * when the mouse enters the applet, and draws "Lost
 * the mouse when the mouse exits the applet.  Provides 
 * an empty body for mouseClicked.
 */

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

public class TryMouse extends Applet
         implements MouseListener {
  private int [] x = {50,100,150};
  private int [] y = {100,50,100};
  private Polygon p = new Polygon(x,y,3);
  private String mouse = "";
 
  public void init() {
    addMouseListener(this);
  }
  public void paint(Graphics g) {
   g.drawString(mouse,20,20);
   g.fillPolygon(p);
  }
  public void mousePressed(MouseEvent event) {
    if (p.contains(event.getX(), event.getY())){
      setForeground(Color.red);
      repaint(); 
    }
  }
  public void mouseReleased(MouseEvent event) {
    if (p.contains(event.getX(), event.getY())){
      setForeground(Color.blue);
      repaint();
    }
  }
  public void mouseClicked(MouseEvent event) {  }
  public void mouseEntered(MouseEvent event) {
    mouse = "Got the mouse";
    repaint();
  }
  public void mouseExited(MouseEvent event) {
    mouse = "Lost the mouse";
    repaint();
  }
}



  
  

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?