Java Tutorial/2D Graphics/Line

Материал из Java эксперт
Версия от 15:24, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A line is drawn using two points

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesDashes1 extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    float[] dash1 = { 2f, 0f, 2f };
    g2d.drawLine(20, 40, 250, 40);
    BasicStroke bs1 = new BasicStroke(1, 
        BasicStroke.CAP_BUTT, 
        BasicStroke.JOIN_ROUND, 
        1.0f, 
        dash1,
        2f);
    g2d.setStroke(bs1);
    g2d.drawLine(20, 80, 250, 80);
    }
  public static void main(String[] args) {
    LinesDashes1 lines = new LinesDashes1();
    JFrame frame = new JFrame("Lines");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(lines);
    frame.setSize(280, 270);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Compares two lines are returns true if they are equal or both null.

import java.awt.geom.Line2D;
public class Main {
  /**
   * Compares two lines are returns <code>true</code> if they are equal or
   * both <code>null</code>.
   *
   * @param l1  the first line (<code>null</code> permitted).
   * @param l2  the second line (<code>null</code> permitted).
   *
   * @return A boolean.
   */
  public static boolean equal(final Line2D l1, final Line2D l2) {
      if (l1 == null) {
          return (l2 == null);
      }
      if (l2 == null) {
          return false;
      }
      if (!l1.getP1().equals(l2.getP1())) {
          return false;
      }
      if (!l1.getP2().equals(l2.getP2())) {
          return false;
      }
      return true;
  }
}





Creates a region surrounding a line segment by "widening" the line segment.

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * -------------------
 * ShapeUtilities.java
 * -------------------
 * (C)opyright 2003-2008, by Object Refinery Limited and Contributors.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: ShapeUtilities.java,v 1.18 2008/06/02 06:58:28 mungady Exp $
 *
 * Changes
 * -------
 * 13-Aug-2003 : Version 1 (DG);
 * 16-Mar-2004 : Moved rotateShape() from RefineryUtilities.java to here (DG);
 * 13-May-2004 : Added new shape creation methods (DG);
 * 30-Sep-2004 : Added createLineRegion() method (DG);
 *               Moved drawRotatedShape() method from RefineryUtilities class
 *               to this class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 26-Oct-2004 : Added a method to test the equality of two Line2D
 *               instances (DG);
 * 10-Nov-2004 : Added new translateShape() and equal(Ellipse2D, Ellipse2D)
 *               methods (DG);
 * 11-Nov-2004 : Renamed translateShape() --> createTranslatedShape() (DG);
 * 07-Jan-2005 : Minor Javadoc fix (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
 * 21-Jan-2005 : Modified return type of RectangleAnchor.coordinates()
 *               method (DG);
 * 22-Feb-2005 : Added equality tests for Arc2D and GeneralPath (DG);
 * 16-Mar-2005 : Fixed bug where equal(Shape, Shape) fails for two Polygon
 *               instances (DG);
 * 01-Jun-2008 : Fixed bug in equal(GeneralPath, GeneralPath) method (DG);
 *
 */
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
/**
 * Utility methods for {@link Shape} objects.
 *
 * @author David Gilbert
 */
public class Main {

  /**
   * Creates a region surrounding a line segment by "widening" the line
   * segment.  A typical use for this method is the creation of a
   * "clickable" region for a line that is displayed on-screen.
   *
   * @param line  the line (<code>null</code> not permitted).
   * @param width  the width of the region.
   *
   * @return A region that surrounds the line.
   */
  public static Shape createLineRegion(final Line2D line, final float width) {
      final GeneralPath result = new GeneralPath();
      final float x1 = (float) line.getX1();
      final float x2 = (float) line.getX2();
      final float y1 = (float) line.getY1();
      final float y2 = (float) line.getY2();
      if ((x2 - x1) != 0.0) {
          final double theta = Math.atan((y2 - y1) / (x2 - x1));
          final float dx = (float) Math.sin(theta) * width;
          final float dy = (float) Math.cos(theta) * width;
          result.moveTo(x1 - dx, y1 + dy);
          result.lineTo(x1 + dx, y1 - dy);
          result.lineTo(x2 + dx, y2 - dy);
          result.lineTo(x2 - dx, y2 + dy);
          result.closePath();
      }
      else {
          // special case, vertical line
          result.moveTo(x1 - width / 2.0f, y1);
          result.lineTo(x1 + width / 2.0f, y1);
          result.lineTo(x2 + width / 2.0f, y2);
          result.lineTo(x2 - width / 2.0f, y2);
          result.closePath();
      }
      return result;
  }
}





Dash style line

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesDashes1 extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    float[] dash1 = { 2f, 0f, 2f };
    g2d.drawLine(20, 40, 250, 40);
    BasicStroke bs1 = new BasicStroke(1, 
        BasicStroke.CAP_BUTT, 
        BasicStroke.JOIN_ROUND, 
        1.0f, 
        dash1,
        2f);
    g2d.setStroke(bs1);
    g2d.drawLine(20, 80, 250, 80);
  }
  public static void main(String[] args) {
    LinesDashes1 lines = new LinesDashes1();
    JFrame frame = new JFrame("Lines");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(lines);
    frame.setSize(280, 270);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Draw a line

import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    g.drawLine(20, 20, 200, 200);
  }
}
public class DrawLine {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}





Draw a point: use a drawLine() method

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Points extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.red);
    for (int i = 0; i <= 100000; i++) {
      Dimension size = getSize();
      int w = size.width ;
      int h = size.height;
      Random r = new Random();
      int x = Math.abs(r.nextInt()) % w;
      int y = Math.abs(r.nextInt()) % h;
      g2d.drawLine(x, y, x, y);
    }
  }
  public static void main(String[] args) {
    Points points = new Points();
    JFrame frame = new JFrame("Points");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(points);
    frame.setSize(250, 200);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Draw Dashed

/*
    GNU LESSER GENERAL PUBLIC LICENSE
    Copyright (C) 2006 The Lobo Project
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    Contact info: lobochief@users.sourceforge.net
*/
import java.awt.*;
public class GUITasks {
  public static Frame getTopFrame() {
    Frame[] frames = Frame.getFrames();
    for(int i = 0; i < frames.length; i++) {
      if(frames[i].getFocusOwner() != null) {
        return frames[i];
      }
    }
    if(frames.length > 0) {
      return frames[0];
    }
    return null;
  }
  
  public static void drawDashed(Graphics g, int x1, int y1, int x2, int y2, int dashSize, int gapSize) {
    if(x2 < x1) {
      int temp = x1;
      x1 = x2;
      x2 = temp;
    }
    if(y2 < y1) {
      int temp = y1;
      y1 = y2;
      y2 = temp;
    }
    int totalDash = dashSize + gapSize;
    if(y1 == y2) {
      int virtualStartX = (x1 / totalDash) * totalDash;
      for(int x = virtualStartX; x < x2; x += totalDash) {
        int topX = x + dashSize;
        if(topX > x2) {
          topX = x2;
        }
        int firstX = x;
        if(firstX < x1) {
          firstX = x1;
        }
        if(firstX < topX) {
          g.drawLine(firstX, y1, topX, y1);
        }
      }
    }
    else if(x1 == x2) {
      int virtualStartY = (y1 / totalDash) * totalDash;
      for(int y = virtualStartY; y < y2; y += totalDash) {
        int topY = y + dashSize;
        if(topY > y2) {
          topY = y2;
        }
        int firstY = y;
        if(firstY < y1) {
          firstY = y1;
        }
        if(firstY < topY) {
          g.drawLine(x1, firstY, x1, topY);
        }
      }     
    }
    else {
      // Not supported
      g.drawLine(x1, y1, x2, y2);
    }
  }
}





draw Line from to

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setSize(400, 400);
    f.add(new MainClass());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
  public void paint(Graphics g) {
    g.drawLine (10, 15, 100, 115);  
  }
}





Line2D.Float

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderControlPaintLine extends JFrame {
  DrawingCanvas canvas = new DrawingCanvas();
  JSlider slider1, slider2, slider3, slider4, slider5, slider6, slider7, slider8;
  double transX = 0.0;
  double transY = 0.0;
  double rotateTheta = 0.0;
  double rotateX = 150.0;
  double rotateY = 150.0;
  double scaleX = 1.0;
  double scaleY = 1.0;
  float width = 1.0f;
  public SliderControlPaintLine() {
    JPanel controlPanel = new JPanel();
    controlPanel.setLayout(new GridLayout(3, 3));
    getContentPane().add(controlPanel, BorderLayout.NORTH);
    JLabel label1 = new JLabel("Translate(dx,dy): ");
    JLabel label2 = new JLabel("Rotate(Theta,ox,oy): ");
    JLabel label3 = new JLabel("Scale(sx,sy)x10E-2:");
    controlPanel.add(label1);
    
    slider1 = createSlider(controlPanel, JSlider.HORIZONTAL, 0, 300, 150, 100, 50);
    slider2 = createSlider(controlPanel, JSlider.HORIZONTAL, 0, 300, 150, 100, 50);
    controlPanel.add(label2);
    
    slider3 = createSlider(controlPanel, JSlider.HORIZONTAL, 0, 360, 0, 90, 45);
    JPanel subPanel = new JPanel();
    subPanel.setLayout(new GridLayout(1, 2));
    slider4 = createSlider(subPanel, JSlider.HORIZONTAL, 0, 300, 150, 150, 50);
    slider5 = createSlider(subPanel, JSlider.HORIZONTAL, 0, 300, 150, 150, 50);
    controlPanel.add(subPanel);
    controlPanel.add(label3);
    
    slider6 = createSlider(controlPanel, JSlider.HORIZONTAL, 0, 200, 100, 100, 10);
    slider7 = createSlider(controlPanel, JSlider.HORIZONTAL, 0, 200, 100, 100, 10);
    JPanel widthPanel = new JPanel();
    JLabel label4 = new JLabel("Width Control:", JLabel.RIGHT);
    slider8 = createSlider(widthPanel, JSlider.HORIZONTAL, 0, 200, 100, 100, 10);
    slider8.addChangeListener(new SliderListener());
    
    widthPanel.setLayout(new GridLayout(1, 2));
    widthPanel.add(label4);
    widthPanel.add(slider8);
    getContentPane().add(widthPanel, BorderLayout.SOUTH);
    getContentPane().add(canvas);
    
    setSize(500,500);
    setVisible(true);
  }
  public static void main(String arg[]) {
    new SliderControlPaintLine();
  }
  public JSlider createSlider(JPanel panel, int orientation, int minimumValue, int maximumValue,
      int initValue, int majorTickSpacing, int minorTickSpacing) {
    JSlider slider = new JSlider(orientation, minimumValue, maximumValue, initValue);
    slider.setPaintTicks(true);
    slider.setMajorTickSpacing(majorTickSpacing);
    slider.setMinorTickSpacing(minorTickSpacing);
    slider.setPaintLabels(true);
    slider.addChangeListener(new SliderListener());
    panel.add(slider);
    return slider;
  }
  class SliderListener implements ChangeListener {
    public void stateChanged(ChangeEvent e) {
      JSlider tempSlider = (JSlider) e.getSource();
      if (tempSlider.equals(slider1)) {
        transX = slider1.getValue() - 150.0;
        canvas.repaint();
      } else if (tempSlider.equals(slider2)) {
        transY = slider2.getValue() - 150.0;
        canvas.repaint();
      } else if (tempSlider.equals(slider3)) {
        rotateTheta = slider3.getValue() * Math.PI / 180;
        canvas.repaint();
      } else if (tempSlider.equals(slider4)) {
        rotateX = slider4.getValue();
        canvas.repaint();
      } else if (tempSlider.equals(slider5)) {
        rotateY = slider5.getValue();
        canvas.repaint();
      } else if (tempSlider.equals(slider6)) {
        if (slider6.getValue() != 0.0) {
          scaleX = slider6.getValue() / 100.0;
          canvas.repaint();
        }
      } else if (tempSlider.equals(slider7)) {
        if (slider7.getValue() != 0.0) {
          scaleY = slider7.getValue() / 100.0;
          canvas.repaint();
        }
      } else if (tempSlider.equals(slider8)) {
        width = slider8.getValue();
        canvas.repaint();
      }
    }
  }
  class DrawingCanvas extends Canvas {
    public DrawingCanvas() {
      setSize(300, 300);
    }
    public void paint(Graphics g) {
      Graphics2D g2D = (Graphics2D) g;
      g2D.translate(transX, transY);
      g2D.rotate(rotateTheta, rotateX, rotateY);
      g2D.scale(scaleX, scaleY);
      BasicStroke stroke = new BasicStroke(width);
      g2D.setStroke(stroke);
      Line2D line1 = new Line2D.Float(100f, 200f, 200f, 200f);
      g2D.draw(line1);
    }
  }
}





Line dashes style 2

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesDashes2 extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawLine(20, 40, 250, 40);
    float[] dash2 = { 1f, 1f, 1f };
    BasicStroke bs2 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash2,2f);
    g2d.setStroke(bs2);
    g2d.drawLine(20, 20, 250, 20);
  }
  public static void main(String[] args) {
    LinesDashes2 lines = new LinesDashes2();
    JFrame frame = new JFrame("Lines");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(lines);
    frame.setSize(280, 270);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Line Dash Style 4

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesDashes4 extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    
    float[] dash4 = { 4f, 4f, 1f };
    BasicStroke bs4 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash4,
        2f);
        
    g2d.setStroke(bs4);
    g2d.drawLine(20, 20, 250, 20);
  }
  public static void main(String[] args) {
    LinesDashes4 lines = new LinesDashes4();
    JFrame frame = new JFrame("Lines");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(lines);
    frame.setSize(280, 270);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Lines Dashes style 3

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesDashes3 extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    
    float[] dash3 = { 4f, 0f, 2f };
    BasicStroke bs3 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash3,
        2f);
    
    g2d.setStroke(bs3);
    g2d.drawLine(20, 60, 250, 60);
  }
  public static void main(String[] args) {
    LinesDashes3 lines = new LinesDashes3();
    JFrame frame = new JFrame("Lines");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(lines);
    frame.setSize(280, 270);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}