日期:2014-05-20 浏览次数:21052 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class DrawLineTest extends JPanel { static int i = 0; int x1[] = new int[10]; int x2[] = new int[10]; int y1[] = new int[10]; int y2[] = new int[10]; public static void main(String[] args) { JFrame frame = new JFrame(); Container container = frame.getContentPane(); DrawLine line = new DrawLine(); frame.add(line); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setTitle("DrawLineTest"); frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); frame.setLocation(200, 200); } public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < x1.length; i++) { g.drawLine(x1[i], y1[i], x2[i], y2[i]); } } public void DrawLine() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent event) { x1[i] = event.getX(); y1[i] = event.getY(); } public void mouseReleased(MouseEvent event) { Graphics g = getGraphics(); g.setColor(Color.RED); x2[i] = event.getX(); y2[i] = event.getY(); g.drawLine(x1[i], y1[i], x2[i], y2[i]); i++; } }); } public static final int DEFAULT_WIDTH = 250; public static final int DEFAULT_HEIGHT = 250; }
import java.awt.Color; import java.awt.Graphics; import java.awt.HeadlessException; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; public class Draw extends JFrame { private Point oldP; private Point newP; public Draw() { this.oldP = new Point(0,0); this.newP = new Point(0,0); this.setBounds(200,50,400,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { oldP = getMousePosition(); } public void mouseReleased(MouseEvent e) { newP = getMousePosition(); repaint(); } }); this.setVisible(true); } public void paint(Graphics g) { Color c = g.getColor(); g.setColor(Color.red); g.drawLine(oldP.x, oldP.y, newP.x, newP.y); g.setColor(c); } public static void main(String[] args) { new Draw(); } }
------解决方案--------------------
楼主的代码贴的好像不怎么全,不知道DrawLine line = new DrawLine();这个类是怎么实现的?
等待。。。。。。
------解决方案--------------------
4楼 正解!
------解决方案--------------------
cmd导入的jar包也要放进相应的路径