Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw lines in Java

Tags:

I'm wondering if there's a funciton in Java that can draw a line from the coordinates (x1, x2) to (y1, y2)?

What I want is to do something like this:

drawLine(x1, x2, x3, x4); 

And I want to be able to do it at any time in the code, making several lines appear at once.

I have tried to do this:

public void paint(Graphics g){    g.drawLine(0, 0, 100, 100); } 

But this gives me no control of when the function is used and I can't figure out how to call it several times.

Hope you understand what I mean!

P.S. I want to create a coordinate system with many coordinates.

like image 584
Karoline Brynildsen Avatar asked Apr 27 '11 09:04

Karoline Brynildsen


People also ask

How do you make a line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What is the method to draw a line in Java?

To answer your original question, it's (x1, y1) to (x2, y2) . This is to draw a vertical line: g. drawLine( 10, 30, 10, 90 );

How do you draw in Java programming?

In the main method, we: Create a JFrame object, which is the window that will contain the canvas. Create a Drawing object (which is the canvas), set its width and height, and add it to the frame. Pack the frame (resize it) to fit the canvas, and display it on the screen.


2 Answers

A very simple example of a swing component to draw lines. It keeps internally a list with the lines that have been added with the method addLine. Each time a new line is added, repaint is invoked to inform the graphical subsytem that a new paint is required.

The class also includes some example of usage.

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList;  import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel;  public class LinesComponent extends JComponent{  private static class Line{     final int x1;      final int y1;     final int x2;     final int y2;        final Color color;      public Line(int x1, int y1, int x2, int y2, Color color) {         this.x1 = x1;         this.y1 = y1;         this.x2 = x2;         this.y2 = y2;         this.color = color;     }                }  private final LinkedList<Line> lines = new LinkedList<Line>();  public void addLine(int x1, int x2, int x3, int x4) {     addLine(x1, x2, x3, x4, Color.black); }  public void addLine(int x1, int x2, int x3, int x4, Color color) {     lines.add(new Line(x1,x2,x3,x4, color));             repaint(); }  public void clearLines() {     lines.clear();     repaint(); }  @Override protected void paintComponent(Graphics g) {     super.paintComponent(g);     for (Line line : lines) {         g.setColor(line.color);         g.drawLine(line.x1, line.y1, line.x2, line.y2);     } }  public static void main(String[] args) {     JFrame testFrame = new JFrame();     testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);     final LinesComponent comp = new LinesComponent();     comp.setPreferredSize(new Dimension(320, 200));     testFrame.getContentPane().add(comp, BorderLayout.CENTER);     JPanel buttonsPanel = new JPanel();     JButton newLineButton = new JButton("New Line");     JButton clearButton = new JButton("Clear");     buttonsPanel.add(newLineButton);     buttonsPanel.add(clearButton);     testFrame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);     newLineButton.addActionListener(new ActionListener() {          @Override         public void actionPerformed(ActionEvent e) {             int x1 = (int) (Math.random()*320);             int x2 = (int) (Math.random()*320);             int y1 = (int) (Math.random()*200);             int y2 = (int) (Math.random()*200);             Color randomColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());             comp.addLine(x1, y1, x2, y2, randomColor);         }     });     clearButton.addActionListener(new ActionListener() {          @Override         public void actionPerformed(ActionEvent e) {             comp.clearLines();         }     });     testFrame.pack();     testFrame.setVisible(true); }  } 
like image 100
jassuncao Avatar answered Oct 28 '22 19:10

jassuncao


Store the lines in some type of list. When it comes time to paint them, iterate the list and draw each one. Like this:

Screenshot

enter image description here

DrawLines

import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.geom.Line2D;  import javax.swing.JOptionPane; import javax.swing.JComponent; import javax.swing.SwingUtilities;  import java.util.ArrayList; import java.util.Random;  class DrawLines {      public static void main(String[] args) {          Runnable r = new Runnable() {             public void run() {                 LineComponent lineComponent = new LineComponent(400,400);                 for (int ii=0; ii<30; ii++) {                     lineComponent.addLine();                 }                 JOptionPane.showMessageDialog(null, lineComponent);             }         };         SwingUtilities.invokeLater(r);     } }  class LineComponent extends JComponent {      ArrayList<Line2D.Double> lines;     Random random;      LineComponent(int width, int height) {         super();         setPreferredSize(new Dimension(width,height));         lines = new ArrayList<Line2D.Double>();         random = new Random();     }      public void addLine() {         int width = (int)getPreferredSize().getWidth();         int height = (int)getPreferredSize().getHeight();         Line2D.Double line = new Line2D.Double(             random.nextInt(width),             random.nextInt(height),             random.nextInt(width),             random.nextInt(height)             );         lines.add(line);         repaint();     }      public void paintComponent(Graphics g) {         super.paintComponent(g);         g.setColor(Color.white);         g.fillRect(0, 0, getWidth(), getHeight());         Dimension d = getPreferredSize();         g.setColor(Color.black);         for (Line2D.Double line : lines) {             g.drawLine(                 (int)line.getX1(),                 (int)line.getY1(),                 (int)line.getX2(),                 (int)line.getY2()                 );         }     } } 
like image 43
Andrew Thompson Avatar answered Oct 28 '22 18:10

Andrew Thompson