Scala/Java 2D: How to draw lines and arcs

This code may not make much sense without seeing the end result, but ... the following source code shows how to draw lines and arcs in Scala and Java:

// thin lines around frame
g2.draw(new Line2D.Double(0, cornerRadius/2, 0, height-cornerRadius/2))                 // left border
g2.draw(new Line2D.Double(width-1, cornerRadius/2, width-1, height-cornerRadius/2))     // right border
g2.draw(new Line2D.Double(cornerRadius/2, 0, width-cornerRadius/2, 0))                  // top border
g2.draw(new Line2D.Double(cornerRadius/2, height-1, width-cornerRadius/2, height-1))    // bottom border

// thin arcs in frame corners
// x, y, rectwidth, rectheight, degreesWhereArcStarts, degreesToSweep, Arc2D.OPEN
// note: zero degrees is the far-right of the x-axis; 90 degrees is the top of the y-axis; 180 is the far-left of the x-axis
// good arc graphic here:
g2.draw(new Arc2D.Double(0, height-cornerRadius, cornerRadius-1, cornerRadius-1, 180, 90, Arc2D.OPEN))                    // bottom-left
g2.draw(new Arc2D.Double(width-cornerRadius, height-cornerRadius, cornerRadius-1, cornerRadius-1, 270, 90, Arc2D.OPEN))   // bottom-right
g2.draw(new Arc2D.Double(0, 0, cornerRadius-1, cornerRadius-1, 90, 90, Arc2D.OPEN))                                       // top-left
g2.draw(new Arc2D.Double(width-cornerRadius-1, 0, cornerRadius-1, cornerRadius-1, 0, 90, Arc2D.OPEN))                     // top-right

I use this code in a project where I have created a replacement for the traditional Java JFrame. I wanted something that looks more interesting than a JFrame, so I’ve created a frame/window that has curved corners, and this is part of the code that makes that happen.

One note about drawing arcs: The fifth and sixth parameters specify (a) the angle at which the arc starts, and (b) the “sweep” of the arc. So the combination of (0, 90) means, “start the arc at the far right, and sweep it up 90 degrees, so it ends at the top-most point.”

paintComponent method

I put this code in a paintComponent method. The old paintComponent method looks like this:

def createContentPane =
    new JComponent {
        override def paintComponent(g: Graphics){
            val g2 = g.create.asInstanceOf[Graphics2D]
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
            val old = g2.getComposite
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alphaComposite))
            val shape = new RoundRectangle2D.Float(0, 0, getWidth, getHeight, cornerRadius, cornerRadius)

I’ll share the new paintComponent method here as soon as I work all the bugs out.

The code shown is written in Scala, but I think you’ll see that it converts easily to Java, if that’s what you need.