在MouseDraged(鼠標按下並拖動時MouseMotionListener)中再GetX();GetY;然後根據第壹個X,Y和第二個X,Y用Graphics類的DrawLine();畫線!
下面的程序參考,沒有實現妳要的功能!註意在畫線時,常常得傳個compenent去getContentPane().
//程序開始
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MouseEventDemo extends JFrame implements MouseListener,MouseMotionListener
{
private JLabel statusBar;
public MouseEventDemo()
{
super("MouseEvent Test");
statusBar=new JLabel("",SwingConstants.LEFT);
getContentPane().add(statusBar,BorderLayout.SOUTH);
addMouseListener(this);
addMouseMotionListener(this);
setSize(300,200);
setVisible(true);
JButton button1=new JButton("確定");
button1.setVisible(true);
button1.setSize(20,20);
getContentPane().add(button1,BorderLayout.NORTH);
}
//以下是對MouseEvent的重寫,因為用implements接口的需要重寫
public void mouseClicked(MouseEvent e)
{
statusBar.setText("Mouse was clicked at position("+e.getX()+","+e.getY()+")");
JOptionPane.showMessageDialog(null,"妳點了壹下鼠標在"+e.getX()+","+e.getY());
}
public void mousePressed(MouseEvent e)
{
statusBar.setText("Mouse was pressed at position("+e.getX()+","+e.getY()+")");
}
public void mouseReleased(MouseEvent e)
{
statusBar.setText("Mouse was released at position("+e.getX()+","+e.getY()+")");
}
public void mouseEntered(MouseEvent e)
{
statusBar.setText("Mouse was entered at position("+e.getX()+","+e.getY()+")");
}
public void mouseExited(MouseEvent e)
{
statusBar.setText("Mouse exited at position("+e.getX()+","+e.getY()+")");
}
//對MouseMotionListener的重寫,獲取鼠標的位置
public void mouseDragged(MouseEvent e)
{
statusBar.setText("Mouse was dragged at position("+e.getX()+","+e.getY()+")");
}
public void mouseMoved(MouseEvent e)
{
statusBar.setText("Mouse was moved at position("+e.getX()+","+e.getY()+")");
}
public static void main(String [] args)
{
MouseEventDemo application=new MouseEventDemo();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
/*extends是繼承父類,只要那個類不是聲明為final或者那個類定義為abstract的就能繼承,JAVA中不支持多重繼承,但是可以用接口來實現,這樣就要用到implements,繼承只能繼承壹個類,但implements可以實現多個接口,用逗號分開就行了
比如
class A extends B implements C,D,E
接口的方法壹般為空的
必須重寫才能使用
*/