当前位置: 技术问答>java相关
怎样在拖动鼠标的时候动态的画出直线?
来源: 互联网 发布时间:2015-01-02
本文导语: 怎样在拖动鼠标的时候动态的画出直线?就像word中的话直线,矩形一样! | import java.awt.*; import java.awt.event.*; public class Test extends java.applet.Applet { Point pBegin; Point pEnd; public void init() { } pu...
怎样在拖动鼠标的时候动态的画出直线?就像word中的话直线,矩形一样!
|
import java.awt.*;
import java.awt.event.*;
public class Test extends java.applet.Applet
{
Point pBegin;
Point pEnd;
public void init()
{
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(Color.white);
if(pBegin==null)
return;
g.drawRect(pBegin.x-1,pBegin.y-1,2,2);
if(pEnd==null)
return;
g.drawLine(pBegin.x,pBegin.y,pEnd.x,pEnd.y);
g.drawRect(pEnd.x-1,pEnd.y-1,2,2);
}
public void update(Graphics g)
{
paint(g);
}
public Test() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
this_mouseMoved(e);
}
});
this.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(MouseEvent e) {
this_mousePressed(e);
}
});
}
void this_mousePressed(MouseEvent e) {
pBegin = e.getPoint();
repaint();
}
void this_mouseMoved(MouseEvent e) {
pEnd = e.getPoint();
repaint();
}
}
import java.awt.event.*;
public class Test extends java.applet.Applet
{
Point pBegin;
Point pEnd;
public void init()
{
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(Color.white);
if(pBegin==null)
return;
g.drawRect(pBegin.x-1,pBegin.y-1,2,2);
if(pEnd==null)
return;
g.drawLine(pBegin.x,pBegin.y,pEnd.x,pEnd.y);
g.drawRect(pEnd.x-1,pEnd.y-1,2,2);
}
public void update(Graphics g)
{
paint(g);
}
public Test() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
this_mouseMoved(e);
}
});
this.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(MouseEvent e) {
this_mousePressed(e);
}
});
}
void this_mousePressed(MouseEvent e) {
pBegin = e.getPoint();
repaint();
}
void this_mouseMoved(MouseEvent e) {
pEnd = e.getPoint();
repaint();
}
}