Search code examples
javaswinggraphicsjava-2d

Java2D: Increase the line width


I want to increase the Line2D width. I could not find any method to do that. Do I need to actually make a small rectangle for this purpose?


Solution

  • You should use setStroke to set a stroke of the Graphics2D object.

    The example at http://www.java2s.com gives you some code examples.

    The following code produces the image below:

    import java.awt.*;
    import java.awt.geom.Line2D;
    import javax.swing.*;
    
    public class FrameTest {
        public static void main(String[] args) {
            JFrame jf = new JFrame("Demo");
            Container cp = jf.getContentPane();
            cp.add(new JComponent() {
                public void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setStroke(new BasicStroke(10));
                    g2.draw(new Line2D.Float(30, 20, 80, 90));
                }
            });
            jf.setSize(300, 200);
            jf.setVisible(true);
        }
    }
    

    enter image description here

    (Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)