如何在画布实现用鼠标拖动画直线,只要直线就行了,尽量简单
展开全部
给你程序,已经尽量简化了。不懂再问吧。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawLine extends JPanel implements MouseListener
{
Point start,end;
public DrawLine()
{
JFrame frame=new JFrame("画线");
frame.setSize(400,300);
frame.add(this,BorderLayout.CENTER);
// addActionListener(this);
addMouseListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new PaintThread().start();
frame.setVisible(true);
}
@Override
public void mousePressed(MouseEvent e)
{
start=new Point(e.getX(),e.getY());
end=null;
}
@Override
public void mouseReleased(MouseEvent e)
{
end=new Point(e.getX(),e.getY());
}
@Override
public void mouseEntered(MouseEvent e){}
@Override
public void mouseExited(MouseEvent e){}
@Override
public void mouseClicked(MouseEvent e){}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(start==null || end==null) return;
Color c=g.getColor();
g.setColor(Color.red);
g.drawLine(start.x,start.y,end.x,end.y);
g.setColor(c);
}
public static void main(String[] args)
{
new DrawLine();
}
private class PaintThread extends Thread
{
@Override
public void run()
{
while(true)
{
repaint();
try
{
Thread.sleep(100);
}
catch(InterruptedException ex)
{}
}
}
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawLine extends JPanel implements MouseListener
{
Point start,end;
public DrawLine()
{
JFrame frame=new JFrame("画线");
frame.setSize(400,300);
frame.add(this,BorderLayout.CENTER);
// addActionListener(this);
addMouseListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new PaintThread().start();
frame.setVisible(true);
}
@Override
public void mousePressed(MouseEvent e)
{
start=new Point(e.getX(),e.getY());
end=null;
}
@Override
public void mouseReleased(MouseEvent e)
{
end=new Point(e.getX(),e.getY());
}
@Override
public void mouseEntered(MouseEvent e){}
@Override
public void mouseExited(MouseEvent e){}
@Override
public void mouseClicked(MouseEvent e){}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(start==null || end==null) return;
Color c=g.getColor();
g.setColor(Color.red);
g.drawLine(start.x,start.y,end.x,end.y);
g.setColor(c);
}
public static void main(String[] args)
{
new DrawLine();
}
private class PaintThread extends Thread
{
@Override
public void run()
{
while(true)
{
repaint();
try
{
Thread.sleep(100);
}
catch(InterruptedException ex)
{}
}
}
}
}
追问
你写的有些我没有学过
不过还是谢谢你了
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2016-05-01
展开全部
今天誓死抵抗
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2016-05-01
展开全部
红旗呢
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询