web-dev-qa-db-ja.com

Javaで三角形を描くにはどうすればよいですか?

さて、まず最初に、g.drawRectまたはg.drawOvalを使用して長方形と円を描画し、電気ショック療法を行う方法を知っていますが、g.drawtriangleがないので、私がいない状態で三角形を描画する方法があるかどうか教えてください三角形の各辺を引き出します。

3
Jack Zhang

Graphics.drawPolygon(int[], int[], int)を使用できます。ここで、最初のint []はx値のセット、2番目のint []はy値のセット、intは配列の長さです。 (三角形の場合、intは3になります)

例:

graphics.drawPolygon(new int[] {10, 20, 30}, new int[] {100, 20, 100}, 3);

出力:

Output

9
Constant

Path2Dオブジェクトを使用し、最初のポイントをmoveTo(...)メソッドで配置してから、lineTo(...)メソッドでポイントを追加します。次に、それを描画するか、Graphics2D#draw(...)およびGraphics2D#fill(...)を介して塗りつぶすことができます。また、その上でclosePath()を呼び出すと、三角形が適切に閉じることを確認できます。

たとえば、次のコードは次を生成します。

enter image description here

import Java.awt.Color;
import Java.awt.Dimension;
import Java.awt.GradientPaint;
import Java.awt.Graphics;
import Java.awt.Graphics2D;
import Java.awt.Paint;
import Java.awt.RenderingHints;
import Java.awt.geom.Path2D;    
import javax.swing.*;

public class Path2DExample extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = PREF_W;
   private static final Color COLOR_1 = Color.blue;
   private static final Color COLOR_2 = Color.red;
   private static final Paint GRADIENT_Paint = new GradientPaint(0, 0, COLOR_1, 20, 20, COLOR_2, true);
   private Path2D myPath = new Path2D.Double();

   public Path2DExample() {
      double firstX = (PREF_W / 2.0) * (1 - 1 / Math.sqrt(3));
      double firstY = 3.0 * PREF_H / 4.0;

      myPath.moveTo(firstX, firstY);
      myPath.lineTo(PREF_W - firstX, firstY);
      myPath.lineTo(PREF_W / 2.0, PREF_H / 4.0);
      myPath.closePath();
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;

      // to smooth out the jaggies
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setPaint(GRADIENT_Paint);  // just for fun!
      g2.fill(myPath);  // fill my triangle
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      Path2DExample mainPanel = new Path2DExample();

      JFrame frame = new JFrame("Path2DExample");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Path2Dオブジェクトを使用することの追加の利点は、Shapeをドラッグする場合、MouseListenerとMouseMotionListenerを使用して、次のように言うのは難しくないことです。

private class MyMouseAdapter extends MouseAdapter {
  private Point pPressed = null;

  @Override
  public void mousePressed(MouseEvent e) {
     if (e.getButton() != MouseEvent.BUTTON1) {
        return;
     }
     if (myPath.contains(e.getPoint())) {
        pPressed = e.getPoint();
     }
  }

  public void mouseDragged(MouseEvent e) {
     drag(e);
  }

  @Override
  public void mouseReleased(MouseEvent e) {
     drag(e);
     pPressed = null;
  }

  private void drag(MouseEvent e) {
     if (pPressed == null) {
        return;
     }
     Point p = e.getPoint();
     int tx = p.x - pPressed.x;
     int ty = p.y - pPressed.y;
     AffineTransform at = AffineTransform.getTranslateInstance(tx, ty);
     myPath.transform(at);
     pPressed = p;
     repaint();
  };

}

全体は次のようになります。

import Java.awt.Color;
import Java.awt.Dimension;
import Java.awt.GradientPaint;
import Java.awt.Graphics;
import Java.awt.Graphics2D;
import Java.awt.Paint;
import Java.awt.Point;
import Java.awt.RenderingHints;
import Java.awt.event.MouseAdapter;
import Java.awt.event.MouseEvent;
import Java.awt.geom.AffineTransform;
import Java.awt.geom.Path2D;
import javax.swing.*;

@SuppressWarnings("serial")
public class Path2DExample extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = PREF_W;
   private static final Color COLOR_1 = Color.blue;
   private static final Color COLOR_2 = Color.red;
   private static final Paint GRADIENT_Paint = new GradientPaint(0, 0, COLOR_1,
         20, 20, COLOR_2, true);
   private Path2D myPath = new Path2D.Double();

   public Path2DExample() {
      double firstX = (PREF_W / 2.0) * (1 - 1 / Math.sqrt(3));
      double firstY = 3.0 * PREF_H / 4.0;

      myPath.moveTo(firstX, firstY);
      myPath.lineTo(PREF_W - firstX, firstY);
      myPath.lineTo(PREF_W / 2.0, PREF_H / 4.0);
      myPath.closePath();

      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setPaint(GRADIENT_Paint);
      g2.fill(myPath);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class MyMouseAdapter extends MouseAdapter {
      private Point pPressed = null;

      @Override
      public void mousePressed(MouseEvent e) {
         if (e.getButton() != MouseEvent.BUTTON1) {
            return;
         }
         if (myPath.contains(e.getPoint())) {
            pPressed = e.getPoint();
         }
      }

      public void mouseDragged(MouseEvent e) {
         drag(e);
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         drag(e);
         pPressed = null;
      }

      private void drag(MouseEvent e) {
         if (pPressed == null) {
            return;
         }
         Point p = e.getPoint();
         int tx = p.x - pPressed.x;
         int ty = p.y - pPressed.y;
         AffineTransform at = AffineTransform.getTranslateInstance(tx, ty);
         myPath.transform(at);
         pPressed = p;
         repaint();
      };

   }

   private static void createAndShowGui() {
      Path2DExample mainPanel = new Path2DExample();

      JFrame frame = new JFrame("Path2DExample");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}