リンクを新しいタブで開く
  1. To draw a line between two points in Java, you can use the Graphics or Graphics2D class, which are part of the java.awt package. Below are two common approaches to achieve this.

    Using Graphics.drawLine()

    This method is straightforward and works well for basic line drawing.

    1. Create a Swing Component Override the paintComponent() method of a JPanel to include the drawing logic.

    2. Draw the Line Use the drawLine(int x1, int y1, int x2, int y2) method of the Graphics object.

    Example Code:

    import javax.swing.*;
    import java.awt.*;

    public class LineDrawingExample extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLUE); // Set line color
    g.drawLine(50, 50, 200, 200); // Draw line from (50, 50) to (200, 200)
    }

    public static void main(String[] args) {
    JFrame frame = new JFrame("Draw Line Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.add(new LineDrawingExample());
    frame.setVisible(true);
    }
    }
    コピーしました。

    Using Graphics2D and Line2D

  1. JavaのdrawLineメソッド―Swing画面に直線、点線、色 …

    JavaのdrawLineメソッドについてまとめています。 JavaのSwingで作成した画面に直線、点線、色変更、曲線、自由に線を引くなど、多数のサンプルコードが …

  2. 他の人も質問しています
  3. Drawing lines examples with Java Graphics2D

    2019年8月10日 · Java Graphics code examples to draw lines with different stroke styles: thickness, dashed.