java Mouse Event的問題【贈20點】

題目:按滑鼠可以有一條線跑出來,當拖拉放開滑鼠後線會消失

我的問題:

一開始要使用mousrPressed嗎?

mouseDragged重繪出來的物件,不會消失嗎?

要怎麼讓它消失呢??是用mouseReleased嗎?

我的方法:

我有用mousrPressed和mouseDragged還有mouseReleased

但那條線只出現一次,之後不管怎麼按都沒有出現那條線了

1 Answer

Rating
  • CK
    Lv 4
    1 decade ago
    Favorite Answer

    簡單寫了一下, 玩玩吧

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    public class MouseDragDrawDemo extends JFrame {

    public MouseDragDrawDemo() {

    getContentPane().add(new DrawingPane(), BorderLayout.CENTER);

    setSize(new Dimension(500, 350));

    setVisible(true);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}

    class DrawingPane extends JPanel implements MouseListener, MouseMotionListener {

    Point startPos = null;

    Point endPos = null;

    public DrawingPane() {

    addMouseListener(this);

    addMouseMotionListener(this);}

    public void mouseClicked(MouseEvent event) {}

    public void mouseEntered(MouseEvent event) {}

    public void mouseExited(MouseEvent event) {}

    public void mousePressed(MouseEvent event) { startPos = event.getPoint(); }

    public void mouseReleased(MouseEvent event) {

    startPos = null;

    endPos = null;

    repaint();}

    public void mouseDragged(MouseEvent event) {

    endPos = event.getPoint();

    repaint();}

    public void mouseMoved(MouseEvent event) {}

    public void paint(Graphics g) {

    Dimension d = getSize();

    g.setColor(Color.black);

    g.fill3DRect(0, 0, d.width, d.height, true);

    if(startPos!=null && endPos!=null) {

    g.setColor(Color.white);

    g.drawLine(startPos.x, startPos.y, endPos.x, endPos.y);

    }}}

    public static void main(String[] args) {

    new MouseDragDrawDemo();

    }}

    Source(s): Me
Still have questions? Get your answers by asking now.