在Java中用箭头画一条线

use*_*501 11 java graphics awt

替代文字任何人都可以指导我如何编码不同方向的箭头线.wa和wl为正,矩形将位于x轴的顶部.下面的示例显示wl是否定且wa是正数.下面的代码显示了我如何编码矩形形状.x1是可变的,表示从x轴开始的位置.e1是形状的长度,wa1和wl1是高度.wsign确定高度wa1或wl1应显示在负侧或正侧.

        if (Math.abs(wl1) > Math.abs(wa1)) {
            y_scale = (load_y0 - 40) / (double) Math.abs(wl1);
        } else {
            y_scale = (load_y0 - 40) / (double) Math.abs(wa1);
        }
        g.drawLine((int) ((double) x0 + x1 * x_scale), (int) (load_y),
                    (int) ((double) x0 + x1 * x_scale),
                    (int) (load_y + (wa1 * y_scale) * -1));
            g.drawLine((int) ((double) x0 + (x1 + e1) * x_scale),
                    (int) (load_y), (int) ((double) x0 + (x1 + e1)
                            * x_scale), (int) (load_y + (wl1 * y_scale)
                            * -1));

            g.drawLine((int) ((double) x0 + x1 * x_scale),
                    (int) (load_y + (wa1 * y_scale * -1)),
                    (int) ((double) x0 + (x1 + e1) * x_scale),
                    (int) (load_y + (wl1 * y_scale) * -1)); 
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 27

这是一个简单的例程(从这里采用)用于绘制任意箭头:

import static java.awt.geom.AffineTransform.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;

public class Main {
    public static void main(String args[]) {
        JFrame t = new JFrame();
        t.add(new JComponent() {

            private final int ARR_SIZE = 4;

            void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
                Graphics2D g = (Graphics2D) g1.create();

                double dx = x2 - x1, dy = y2 - y1;
                double angle = Math.atan2(dy, dx);
                int len = (int) Math.sqrt(dx*dx + dy*dy);
                AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
                at.concatenate(AffineTransform.getRotateInstance(angle));
                g.transform(at);

                // Draw horizontal arrow starting in (0, 0)
                g.drawLine(0, 0, len, 0);
                g.fillPolygon(new int[] {len, len-ARR_SIZE, len-ARR_SIZE, len},
                              new int[] {0, -ARR_SIZE, ARR_SIZE, 0}, 4);
            }

            public void paintComponent(Graphics g) {
                for (int x = 15; x < 200; x += 16)
                    drawArrow(g, x, x, x, 150);
                drawArrow(g, 30, 300, 300, 190);
            }
        });

        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.setSize(400, 400);
        t.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述