使用JAVA AWT mousemotionlistener在Java applet中绘制动态线条?

时间:2015-08-04 02:14:09

标签: java applet

所以,这就是事情。我的讲师教我们如何通过点击applet获得鼠标坐标。现在,我想我可以尝试使用mousedrag方法和鼠标坐标使用mousemotionlistener类绘制动态线条。我尝试过但却无法真正发挥作用。任何人都可以建议我在哪里犯了错误。非常感谢。

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.applet.*;

public class drawing extends Applet
implements MouseMotionListener {  

    int mx,my;
    Graphics2D g2;

    public void init()
    {
        this.addMouseMotionListener(this);

    }

    public void paint(Graphics g)
    {
        this.setSize(800,600);

         g2 = (Graphics2D) g;
         g2.setStroke(new BasicStroke(10));
         g2.drawLine(40,50,200,150); // I was experimenting to draw static lines using the drawLine() method. 
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        // TODO Auto-generated method stub

        mx = e.getX();
        my = e.getY();
        System.out.println(" "+ mx + " "+ my);
        g2.setStroke(new BasicStroke(10));
        g2.drawLine(mx,my,mx,my); 



    }

    @Override
    public void mouseMoved(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }



}

1 个答案:

答案 0 :(得分:1)

为了绘制一条线,您需要知道起点(用户点击的点)和终点(用户拖动到的点),从简单的事情到简单的使用Graphics#drawLine

首先查看How to Write a Mouse Listener2D GraphicsPainting in AWT and Swing了解详情

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class Drawing extends Applet
                implements MouseMotionListener, MouseListener {

    private Point startPoint, endPoint;

    public void init() {
        this.addMouseMotionListener(this);
        addMouseListener(this);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (startPoint != null && endPoint != null) {
            g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        endPoint = e.getPoint();
        repaint();
    }

    @Override
    public void mouseMoved(MouseEvent arg0) {

    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
        startPoint = e.getPoint();
        endPoint = e.getPoint();
        repaint();
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

}

现在,我的建议是,不要直接使用Applet或AWT。相反,请从JPanel开始并覆盖它的paintComponent方法并使用它执行自定义绘画。然后将此面板添加到JFrame以在屏幕上显示。

AWT超过15年已经过时了,applet已经解决了许多你现在不需要处理的陷阱。

首先看看Creating a GUI With JFC/Swing,或者甚至对JavaFX进行一些研究