View Single Post
  #2 (permalink)  
Old 01-19-2008, 12:24 PM
hardwired hardwired is online now
Senior Member
 
Join Date: Jul 2007
Posts: 1,266
hardwired is on a distinguished road
Code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LineTest extends JPanel { Point p1 = new Point(); Point p2 = new Point(); protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.red); g2.fillOval(p1.x-2, p1.y-2, 4, 4); g2.setPaint(Color.green.darker()); g2.fillOval(p2.x-2, p2.y-2, 4, 4); g2.setPaint(Color.blue); drawLine(p1.x, p1.y, p2.x, p2.y, g2); } private void drawLine(int x1, int y1, int x2, int y2, Graphics2D g) { int dX = 0, dY = 0; //device x and y int xMin = Math.min(x1, x2); int yMin; // Everything is upside-down. //Calculate the slope // Origin of this is at upper left; origin of // cartesian coordinate system is at lower left. // Therefore, reverse the sign for the rise: double rise = -(double)(y2 - y1); double run = (double)(x2 - x1); double slope = rise / run; System.out.printf("slope = %.3f rise = %.0f run = %.0f%n", slope, rise, run); if (slope > 0) // posetive slope rises left to right { yMin = Math.max(y1, y2); if (Math.abs(rise) >= Math.abs(run)) // slope > 1.0 { for (int y = 0; y <= Math.abs(rise); y++) { dY = yMin - y; dX = (int)(xMin + (y/slope)); g.drawOval(dX-2, dY-2, 4, 4); } } else // 0 < slope < 1.0 { for(int x = 0; x <= Math.abs(run); x++) { dY = (int)(yMin - (slope*x)); dX = xMin + x; g.drawOval(dX-2, dY-2, 4, 4); } } } } public static void main(String[] args) { LineTest test = new LineTest(); test.addMouseListener(test.ma); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(test); f.setSize(400,400); f.setLocationRelativeTo(null); f.setVisible(true); } private MouseAdapter ma = new MouseAdapter() { int pointCount = 0; public void mousePressed(MouseEvent e) { Point p = e.getPoint(); switch(pointCount) { case 0: p1 = p; break; case 1: p2 = p; } System.out.printf("p1 = [%d, %d] p2 = [%d, %d]%n", p1.x, p1.y, p2.x, p2.y); repaint(); pointCount++; if(pointCount > 1) pointCount = 0; } }; }
Reply With Quote