14

I am making a basic Java program and I would like to draw a line using basic swing Graphics.drawLine.

Is there a way to make the two points in terms of doubles so I can make the output more accurate, or another way that is better?

aioobe
  • 413,195
  • 112
  • 811
  • 826
Adrian D'Urso
  • 273
  • 3
  • 4
  • 10

2 Answers2

25

You can draw the lines using ((Graphics2D) g).draw(Shape) and pass it a Line2D.Double.

Here's a demo:

enter image description here

import javax.swing.*;

public class FrameTestBase extends JFrame {

    public static void main(String args[]) {
        FrameTestBase t = new FrameTestBase();
        t.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                for (int i = 0; i < 50; i++) {
                    double delta = i / 10.0;
                    double y = 5 + 5*i;
                    Shape l = new Line2D.Double(5, y, 200, y + delta);
                    g2.draw(l);
                }
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 400);
        t.setVisible(true);
    }
}

You might also want to try adding

g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
                    RenderingHints.VALUE_STROKE_PURE)
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • @aioobe why so convoluted answer while simple 1 line was enough? – ring bearer Oct 13 '11 at 20:01
  • 6
    @ringbearer, because a future googler / visitor should quickly and easily be able to tell whether or not this answer suits their needs. For graphics related questions and answers, a screen-shot is usually the best way to illustrate what problem the answer solves. – aioobe Oct 13 '11 at 20:03
  • 2
    As you can see in the screenshot, this hasn't made any difference. It only works if you combine it with `g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE)`. See this question: http://stackoverflow.com/questions/12415640/is-there-any-way-to-draw-lines-with-subpixel-precision-in-swing – Luigi Plinge Sep 13 '12 at 23:24
15

If you have a refernce to g, which I assume is Graphics object, you should use Java 2D APIs

Graphics2D g2 = (Graphics2D) g;
g2.draw(new Line2D.Double(x1, y1, x2, y2));

Javadocs for:

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ring bearer
  • 20,383
  • 7
  • 59
  • 72