3

I'm trying to write a simple paint applet with Java, but I'm having trouble with BasicStroke. Initially, my plan was to try to somehow draw a line with a width, but the API apparently doesn't support that.

I tried using BasicStroke, but the result is just a fuzzy mess. How can I fix this fuzz problem?

typical result

private void mousedrag_hook(Point point)
    {
        if(start == null)
            start = point;

            end = point;

            Graphics2D g2d = (Graphics2D)applInstance.buffer_g;
            g2d.setStroke(new BasicStroke(7));

            //g2d.fillOval(point.x - 5, point.y - 5, 10, 10);
            g2d.drawLine(start.x, start.y, end.x, end.y);
            applInstance.repaint();

            start = end;
    }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user830713
  • 155
  • 2
  • 6
  • 2
    That doesn't look fuzzy to me at all. In fact, just the opposite: it looks jagged and sharp when some anti-aliasing would make it looks straight and soft. – Mark Peters Aug 09 '11 at 05:58

1 Answers1

5

Don't forget the RenderingHints:

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    ...
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • See also this related [example](http://stackoverflow.com/questions/5797862/draw-a-line-in-a-jpanel-with-button-click-in-java/5797965#5797965). – trashgod Aug 09 '11 at 08:21
  • Thank you! With the anti aliasing and the round butt, it looks much better now. However, I have noticed that with MS Paint, after you finish the stroke, most of the "edges" get removed, and the line looks much smoother. Is there a simple algorithm that can do this? – user830713 Aug 09 '11 at 17:31
  • Yes, accumulate the essential points in a `GeneralPath`, as shown [here](http://stackoverflow.com/questions/6694417/draw-polar-graph-in-java/6697773#6697773). You can accept this answer by clicking the check to the left, as discussed in the [faq#reputation]. – trashgod Aug 09 '11 at 21:42