How to draw lines in Java


Karoline Brynildsen:

I was wondering if there is a function in Java to draw a line from coordinates (x1,x2) to (y1,y2)?

What I want to do is something like this:

drawLine(x1, x2, x3, x4);

And I'd like to be able to do this at any point in the code so that multiple lines appear at the same time.

I am trying to do this:

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

However, this leaves me with no control over when the function is used, and I can't figure out how to call it multiple times.

Hope you get what I mean!

PS I want to create a coordinate system with many coordinates.

jassuncao:

A very simple example of a swing component that draws lines. It internally keeps a list with the lines added using the method addLine. Every time a new row is added, repaint is called to notify the graphics subsystem that a new paint is required.

The class also includes some usage examples.

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);
}

}

Related


How to draw lines in Java

Karoline Brynildsen: I was wondering if there is a function in Java to draw a line from coordinates (x1,x2) to (y1,y2)? What I want to do is something like this: drawLine(x1, x2, x3, x4); And I'd like to be able to do this at any point in the code so that mul

How to draw lines in Java

Karoline Brynildsen: I was wondering if there is a function in Java to draw a line from coordinates (x1,x2) to (y1,y2)? What I want to do is something like this: drawLine(x1, x2, x3, x4); And I'd like to be able to do this at any point in the code so that mul

How to draw lines above text in Java

envious: I want to draw a line above Java text. I use graphics and this is my code: String s = a.getSequent().toString(); FontMetrics fm = getFontMetrics(getFont()); int textHeight = fm.getHeight(); int textWidth= fm.stringWidth(s); //Text g.drawString( s,

How to draw lines above text in Java

envious: I want to draw a line above Java text. I use graphics and this is my code: String s = a.getSequent().toString(); FontMetrics fm = getFontMetrics(getFont()); int textHeight = fm.getHeight(); int textWidth= fm.stringWidth(s); //Text g.drawString( s,

How to draw lines above text in Java

envious: I want to draw a line above Java text. I use graphics and this is my code: String s = a.getSequent().toString(); FontMetrics fm = getFontMetrics(getFont()); int textHeight = fm.getHeight(); int textWidth= fm.stringWidth(s); //Text g.drawString( s,

How to draw lines on plots?

Bubisi I'm trying to draw a line on a line, but the plot doesn't even show. I have checked the values of xPoints and yPoints and they exist. what is the reason? import matplotlib.pyplot as plt import numpy as np def calculateFuncFor(x): ePower = np.e**np.

How to draw lines on plots?

Bubisi I'm trying to draw a line on a line, but the plot doesn't even show. I have checked the values of xPoints and yPoints and they exist. what is the reason? import matplotlib.pyplot as plt import numpy as np def calculateFuncFor(x): ePower = np.e**np.

How to draw "curved" lines?

Daniel The problem is simple, as the title says. Tizen's documentation is really unreliable on this topic (among others). For example, as they describe here : Draw SVG paths. You can use the api in efl_gfx_utils.h to construct the path ... efl_gfx_path_append_

How to draw lines on canvas

Arun Kumar I want to draw some lines inside a circle on canvas in the following way. I don't know how to draw lines like below. But I have basic knowledge of drawing lines and arcs on canvas. how to proceed? username You could use a bezier curve with control p

How to draw lines on canvas?

monkey 334 I've read some tutorials on the internet but I can't seem to find any way to show me the lines Can someone help? i try to do p = Canvas(height = 600, width = 800).place(x=0,y=0) p.create_rectangle(50, 25, 150, 75, fill="blue") Unfortunately, it did

How to draw lines on plots?

Bubisi I'm trying to draw a line on a line, but the plot doesn't even show. I have checked the values of xPoints and yPoints and they exist. what is the reason? import matplotlib.pyplot as plt import numpy as np def calculateFuncFor(x): ePower = np.e**np.

How to draw "curved" lines?

Daniel The problem is simple, as the title says. Tizen's documentation is really unreliable on this topic (among others). For example, as they describe here : Draw SVG paths. You can use the api in efl_gfx_utils.h to construct the path ... efl_gfx_path_append_

Java JFrame draw multiple lines

username So the crux of my problem is combining multiple components into a single component JFramein Java . I've tried to use the same component twice to draw two different lines, but only one appears. I'm using three separate classes in separate files, which

Java input coordinates and draw lines

username How can I draw a line in Java if I pass an input like (1,1)(2,2)(3,3). The number of points may vary like (1,1)(2,2). Really hard to get it to work. See the code below import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; impo

CSS: How to draw vertical lines with tabbed lines

Judas I have CSS homework. My job is to draw bus routes. Here is my html: <div class="city-group"> <div class="city-name-wrapper"> <div class="city-name-line"> <div class="city-name">City 1</div> </div> </div> <div class="stop-list"> <

CSS: How to draw vertical lines with tabbed lines

Judas I have CSS homework. My job is to draw bus routes. Here is my html: <div class="city-group"> <div class="city-name-wrapper"> <div class="city-name-line"> <div class="city-name">City 1</div> </div> </div> <div class="stop-list"> <

CSS: How to draw vertical lines with tabbed lines

Judas I have CSS homework. My job is to draw bus routes. Here is my html: <div class="city-group"> <div class="city-name-wrapper"> <div class="city-name-line"> <div class="city-name">City 1</div> </div> </div> <div class="stop-list"> <

How to draw lines on an image in OpenCV?

Rahul: If I have polar coordinates of a line, how can I draw it on an image in OpenCV and python? LineThe function takes 2 points, but only draws line segments. I want to draw a line from one edge of an image to the other. Robert Caspary: Just count 2 points.

How to quickly draw dashed lines?

A. Stability: I would like to know how to quickly draw a dashed line like this:------- instead of a regular straight line like this:---------------- Knowing that I can write multiple lines, but It would take a lot of unnecessary code if I could just write one

How to draw vertical lines of octaves?

Austin A What's the best way to draw vertical lines using octave? Austin A So I have two methods. I found one and I made up the other. Method 1: Start here . %% Set x value where verticle line should intersect the x-axis. x = 0; %% plot a line between two poin

How to Draw Diagonal Lines with CSS

Server Khalilov I need to draw my div diagonally. It should look like this: my HTML: <div style="height: 28px; width: 28px; border: 1px solid rgb(219,225,230);background-color:white;" > </div> Is it possible to do this using only CSS? Kheema Pandey The de

How to draw dashed lines in Firemonkey?

Craig I want to draw a dotted grid on the TPaintbox canvas of a Firemonkey project and the result should look exactly like this: First, I want to draw vertical dashed lines first, and then horizontal dashed lines, so with that in mind, I tried to draw a straig

How to draw multiple lines on pandas?

French coffee Say I have the following pandasdataframe: In[114]: df Out[114]: 0-10% 11-20% 21-30% 31-40% 41-50% 51-60% 61-70% 71-80% 81-90% \ f 0.186 3.268 3.793 4.554 6.421 6.345 7.383 8.476 8.968 l 1.752 2.205 2.50

How to draw lines into numpy arrays?

Martin Thoma: I would like to be able to plot lines into numpy arrays for offline functionality for online handwriting recognition. This means that I don't need an image at all, but I need an image that looks like a given size at certain positions in the numpy

Basics of LiveCharts - How to draw lines?

McCormick I'm having a hard time understanding what's actually happening with LiveCharts. I have a XAML block here: <Grid> <Grid.Background> <ImageBrush ImageSource="/CPF;component/Images/background-top-cropped2.png" Stretch="None"></ImageBrush>

How to draw lines between circles?

blue sky I am planning to draw three circles and draw connecting lines between each circle. The ultimate goal is to configure the circles to connect using json config, but until then I'm just trying to connect the circles with callbacks and hardcoded values. H

How to Draw Diagonal Lines with CSS

Server Khalilov I need to draw div diagonal. It should look like this: my HTML: <div style="height: 28px; width: 28px; border: 1px solid rgb(219,225,230);background-color:white;" > </div> Is it possible to do this using only CSS? Kheema Pandey The desired

How to draw lines on Google Maps

Eastwood I have a lot of user coordinates from a server and I want to draw lines connecting such users . I tried this way, but my app crashes, I guess it happens because I send too many requests. take The easiest way is to use GMSPolyline. Suppose you have an

How to draw directed lines in matplotlib?

Wallace In matplotlib, using plt.plot(xs, ys, '-'+marker). This gives you an undirected line, and you can't tell by looking at the resulting plot which end corresponds to the beginning of the array of data points and which corresponds to the end of the array.