testmouseevent.java

来自「此源码为机械工业出版社出版的《Java语言程序设计》第三版所配套的书中所有源代码」· Java 代码 · 共 64 行

JAVA
64
字号
// TestMouseEvent.java: Move a message in a panel
// by dragging the mouse
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TestMouseEvent extends JFrame
{
  // Default constructor
  public TestMouseEvent()
  {
    // Create a MoveMessagePanel instance for drawing a message
    MoveMessagePanel p = new MoveMessagePanel("Welcome to Java");

    // Place the message panel in the frame
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(p);
  }

  // Main method
  public static void main(String[] args)
  {
    TestMouseEvent frame = new TestMouseEvent();
    frame.setTitle("Move Message Using Mouse");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }

  // MoveMessagePanel draws a message
  // This class is defined as inner class
  class MoveMessagePanel extends MessagePanel
    implements MouseMotionListener
  {
    // Construct a panel to draw string s
    public MoveMessagePanel(String s)
    {
      super(s);
      this.addMouseMotionListener(this);
    }

    // Tell the panel how to draw things
    public void paintComponent(Graphics g)
    {
      // Invoke the paintComponent method in the MessagePanel class
      super.paintComponent(g);
    }

    // Handler for mouse moved event
    public void mouseMoved(MouseEvent e)
    {
    }

    // Handler for mouse dragged event
    public void mouseDragged(MouseEvent e)
    {
      // Get the new location and repaint the screen
      setXCoordinate(e.getX());
      setYCoordinate(e.getY());
      repaint();
    }
  }
}

⌨️ 快捷键说明

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