Line2D Java Example
Draw a straight line is one of the easiest things to do with Java2D. This is achieved through the Line2D class, whose constructor accepts four parameters, namely the coordinates of the start and end respectively.
In Line2D Java Example we are using package java.awt.geom.*. This class provides a line segment in (x, y) coordinate space. Following is at able that lists some of the Constructors and methods of Line2D class:
Constructors and Methods
Description
Creates a Line2D from (0, 0) to (0, 0).
Line2D.Double (double X1, double Y1, double X2, double Y2)
Creates a Line2D from (X1, Y1) to (X2, Y2).
Creates a Line2D from (0, 0) to (0, 0).
Line2D.Float (float X1, float Y1, float X2, float Y2)
Creates a Line2D from (X1, Y1) to (X2, Y2).
intersects (double X, double Y, double W, double H)
Returns true if the rectangle described by (X, Y, Width, Height) intersects the Line.
intersectsLine (double X1, double Y1, double X2, double Y2)
Returns true if the line from (X1, Y1) to (X2, Y2) intersects the Line.
Returns true if the line L intersects the Line.
setLine (double X1, double Y1, double X2, double Y2)
Sets the ends of the line as (X1, Y1) and (X2, Y2).
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.image.*;
public class Draw2DLineExample extends Applet
public static void main(String[] args)
Frame Draw2DLine = new Frame("Draw Line2D Example");
Draw2DLine.setSize(350, 250);
Applet Draw2DLineExample = new Draw2DLineExample();
Draw2DLine.add(Draw2DLineExample);
Draw2DLine.setVisible(true);
Draw2DLine.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
>
>);
>
public void paint(Graphics g)
g.setColor(Color.blue);
g.setFont(new Font("Arial",Font.BOLD,14));
g.drawString("Draw 2D Line Example", 50, 40);
g.setFont(new Font("Arial",Font.BOLD,10));
g.drawString("http://ecomputernotes.com", 200, 205);
super.paint(g);
Graphics2D G2D = (Graphics2D)g;
G2D.setColor(Color.pink);
G2D.setStroke(new BasicStroke(3.0f));
Line2D L2D = new Line2D.Float(50.0f, 50.0f, 200.0f, 200.0f);
G2D.draw(L2D);
>
>
Иллюстрированный самоучитель по программированию мобильных телефонов
Для того чтобы нарисовать линию нужно воспользоваться методом draw-Line () класса Graphics. Рассмотрим прототип этого метода:
public void drawLine(int x 1, int y 1, int x2, int y2)
Параметры метода drawLine ():
- x1 – координата начальной точки отрезка по оси X;
- у1 – координата начальной точки отрезка по оси Y;
- х2 – координата конечной точки отрезка по оси X;
- у2 – координата конечной точки отрезка по оси Y.
Задавая целочисленные координаты точек в методе drawLine () можно нарисовать любую линию заданного размера. Также можно воспользоваться методом setColor () для закрашивания линий цветом и методом setStrokeSty le () – для рисования линии в виде пунктира.
Рассмотрим пример кода находящийся в листинге 7.1, где с помощью линий рисуется система координат используемая в Java 2 ME.
Листинг 7.1. Класс Main и класс Line.
import javax..microedition.lcdui.*; import javax.microedition.midlet.*; public class Main extends MIDlet implements CommandListener < // команда выхода из программы private Command exitMidlet = new Command("Выход",Command.EXIT, 0); public void startApp() < // создаем объект класса Line Line myline = new Line(); // добавляем команду выхода myline.addCommand(exitMidlet); myline.setCommandListener(this); Display.getDisplay(this).setCurrent(myline); >public void pauseApp() <> public void destroyApp(boolean unconditional)<> public void commandAction(Command c, Displayable d) < if (c = = exitMidlet) < destroyApp(false); notifyDestroyed(); >> > /** класс Line определен в файле Line.Java */ import javax.microedition.Icdui.*; public class Line extends Canvas < // конструктор public Line()< super(); >public void paint(Graphics g) < // устанавливается синий цвет для линий g.setColor(0x0000ff); // рисуется система координат g.drawLine(20, 20, 90, 20); g.drawLine(20, 20, 20, 90) g.drawLine(90, 20, 80, 10) g.drawLine(90, 20, 80, 30) g.drawLine(20, 90, 10, 80) g.drawLine(20, 90, 30, 80) // устанавливается красный цвет для трех линий g.setColor(0xffff0000); // рисуем толстую линию, в три пикселя g.drawLine(30, 30, 70, 30); g.drawLine(30, 31, 70, 31); g.drawLine(30, 32, 70, 32); // устанавливаем пунктир g.setStrokeStyle(Graphics.DOTTED); // рисуем линию в два пикселя пунктиром g.drawLine(30, 50, 70, 50); g.drawLine(30, 51, 70, 51); >>
В листинге 7.1 используются два класса: Main, являющийся основным классом мидлета приложения, и класс Line, в котором происходит работа с графикой. Подразумевается, что оба класса находятся в файлах Main.java и Line.java, это характерно для объектно-ориентированного программирования и в дальнейшем мы будем придерживаться именно такой модели построения изучаемых примеров.
How do I draw a line in Java 2D?
The following code snippet show you how to draw a simple line using Graphics2D.draw() method. This method take a parameter that implements the java.awt.Shape interface.
To draw a line we can use the Line2D.Double static-inner class. This class constructor takes four integers values that represent the start (x1, y1) and end (x2, y2) coordinate of the line.
package org.kodejava.awt.geom; import javax.swing.*; import java.awt.*; import java.awt.geom.Line2D; public class DrawLine extends JComponent < public static void main(String[] args) < JFrame frame = new JFrame("Draw Line"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new DrawLine()); frame.pack(); frame.setSize(new Dimension(420, 440)); frame.setVisible(true); >@Override public void paint(Graphics g) < // Draw a simple line using the Graphics2D draw() method. Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(2f)); g2.setColor(Color.RED); g2.draw(new Line2D.Double(50, 150, 250, 350)); g2.setColor(Color.GREEN); g2.draw(new Line2D.Double(250, 350, 350, 250)); g2.setColor(Color.BLUE); g2.draw(new Line2D.Double(350, 250, 150, 50)); g2.setColor(Color.YELLOW); g2.draw(new Line2D.Double(150, 50, 50, 150)); g2.setColor(Color.BLACK); g2.draw(new Line2D.Double(0, 0, 400, 400)); >>
When you run the snippet it will show you something like:
A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏
Drawing Lines
is used to draw a straight line from point (x1,y1) to (x2,y2).
Source: (DrawLine.java)
import java.awt.*; import javax.swing.*; public class DrawLine extends JPanel { public void paintComponent(Graphics g) { //vertical line g.setColor(Color.red); g.drawLine(20, 20, 20, 120); //horizontal line g.setColor(Color.green); g.drawLine(20, 20, 120, 20); //diagonal line g.setColor(Color.blue); g.drawLine(20, 20, 120, 120); } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Draw Line"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBackground(Color.white); frame.setSize(200, 200); DrawLine panel = new DrawLine(); frame.add(panel); frame.setVisible(true); } }
Output:
$ java DrawLine
Questions answered by this page:
Java swing draw line. How to draw a vertical line in Swing? How to draw a horizontal line in java swing? How to draw a diagonal line in java swing? Using Graphics to draw lines.
Line on java mobile
- Language
- HTML & CSS
- Form
- Java interaction
- Mobile
- Varia
- Language
- String / Number
- AWT
- Swing
- Environment
- IO
- JS interaction
- JDBC
- Thread
- Networking
- JSP / Servlet
- XML / RSS / JSON
- Localization
- Security
- JNI / JNA
- Date / Time
- Open Source
- Varia
- Powerscript
- Win API & Registry
- Datawindow
- PFC
- Common problems
- Database
- WSH & VBScript
- Windows, Batch, PDF, Internet
- BigIndex
- Download
- TS2068, Sinclair QL Archives
- Real’s HowTo FAQ
- Donate!
- Funny 1
- Funny 2
- Funny 3
- Funny 4
- One line
- Ascii Art
- Deprecated (old stuff)
Draw a line with a thickness Tag(s): AWT
About cookies on this site
We use cookies to collect and analyze information on site performance and usage, to provide social media features and to enhance and customize content and advertisements.
import java.awt.*; import java.applet.*; public class thickLine extends Applet < public void init( ) < >public void paint( Graphics g ) < drawThickLine (g, 0, 0, getSize().width, getSize().height, 5, new Color(0).black); drawThickLine (g, 0, getSize().height, getSize().width, 0, 5, new Color(0).red); drawThickLine (g, getSize().width/2, 0, getSize().width/2, getSize().height, 8, new Color(0).green); drawThickLine (g, 0, getSize().height/2, getSize().width, getSize().height/2, 12, new Color(0).blue); >public void drawThickLine( Graphics g, int x1, int y1, int x2, int y2, int thickness, Color c) < // The thick line is in fact a filled polygon g.setColor(c); int dX = x2 - x1; int dY = y2 - y1; // line length double lineLength = Math.sqrt(dX * dX + dY * dY); double scale = (double)(thickness) / (2 * lineLength); // The x,y increments from an endpoint needed to create a rectangle. double ddx = -scale * (double)dY; double ddy = scale * (double)dX; ddx += (ddx >0) ? 0.5 : -0.5; ddy += (ddy > 0) ? 0.5 : -0.5; int dx = (int)ddx; int dy = (int)ddy; // Now we can compute the corner points. int xPoints[] = new int[4]; int yPoints[] = new int[4]; xPoints[0] = x1 + dx; yPoints[0] = y1 + dy; xPoints[1] = x1 - dx; yPoints[1] = y1 - dy; xPoints[2] = x2 - dx; yPoints[2] = y2 - dy; xPoints[3] = x2 + dx; yPoints[3] = y2 + dy; g.fillPolygon(xPoints, yPoints, 4); > >
public void paint(Graphics g)
int width = 10; BasicStroke bs = new BasicStroke(width); JLabel l = new JLabel(); l.getGraphics().setStroke(bs); l.drawLine(0,0,100,100);
import javax.swing.*; import java.awt.*; import java.awt.geom.*; public class TestLine extends JFrame < private MyPanel panel; public TestLine() < setSize(200, 200); panel = new MyPanel(); getContentPane().add( panel, "Center" ); >public static void main( String [] args ) < TestLine tl = new TestLine(); tl.setVisible( true ); >> class MyPanel extends JPanel < final static BasicStroke stroke = new BasicStroke(2.0f); final static BasicStroke wideStroke = new BasicStroke(8.0f); public MyPanel()<>public void paintComponent( Graphics g ) < Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setStroke( stroke ); g2.draw(new Line2D.Double(10.0, 10.0, 100.0, 10.0)); g2.setStroke( wideStroke ); g2.draw(new Line2D.Double(10.0, 50.0, 100.0, 50.0)); >>