- Java code
import java.awt.*;import java.awt.event.*;import java.util.*;import java.util.List;public class Draw { public static void main(String args[]){ MyFrame f=new MyFrame("drawing"); }}class MyFrame extends Frame{ ArrayList<ArrayList<Point>>alllines=new ArrayList<ArrayList<Point>>(); ArrayList<Point>points=new ArrayList<>(); public MyFrame(String tit){ super(tit); setBounds(300,300,300,300); setVisible(true); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); this.addMouseMotionListener(new MouseMotionAdapter(){ public void mouseDragged(MouseEvent e) { points.add(new Point(e.getX(),e.getY())); alllines.add(points); repaint(); } }); } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ for(Iterator<ArrayList<Point>>i=alllines.iterator();i.hasNext();){ for(Iterator<Point>j=i.next().iterator();j.hasNext();){ int x1=0,x2=0,y1=0,y2=0; Point p=(Point)j.next(); x2=(int)p.getX(); y2=(int)p.getY(); if(x1!=0)g.drawLine(x1, y1, x2, y2); x1=x2; y1=y2; repaint(); } }} }
不管我怎么点就是没有任何的线条,这是为什么啊,我是菜鸟,可以的话请详解,谢谢各位了!
------解决方案--------------------
这个就是一些小逻辑问题了,参考下吧,可以单独画线了。
增加了对鼠标按下的事件监听器。
具体修正部分见程序中的注释:
- Java code
import java.awt.*;import java.awt.event.*;import java.util.*;import java.util.List;public class Draw { public static void main(String args[]){ MyFrame f=new MyFrame("drawing"); }}class MyFrame extends Frame{ ArrayList<ArrayList<Point>>alllines=new ArrayList<ArrayList<Point>>(); ArrayList<Point>points=new ArrayList<Point>(); // Added below private int x1, x2, y1, y2; // End public MyFrame(String tit){ super(tit); setBounds(300,300,300,300); setVisible(true); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); this.addMouseMotionListener(new MouseMotionAdapter(){ public void mouseDragged(MouseEvent e) { // System.out.println("(" + e.getX() + ", " + e.getY() + ")"); points.add(new Point(e.getX(),e.getY())); alllines.add(points); repaint(); } }); // Added below this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { x1 = y1 = x2 = y2 = 0; points.clear(); } }); // End } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ for(Iterator<ArrayList<Point>>i=alllines.iterator();i.hasNext();){ // Modified below x1 = y1 = x2 = y2 = 0; // End for(Iterator<Point>j=i.next().iterator();j.hasNext();){ Point p=(Point)j.next(); x2=(int)p.getX(); y2=(int)p.getY(); if(x1!=0)g.drawLine(x1, y1, x2, y2); x1=x2; y1=y2; // repaint(); } } }}