Search code examples
javaswingjbuttoncustom-componentrounded-corners

How to make Round JButtons in Java


First, I am a Web Developer and a novice Java programmer. My boss is asking me to make this button in an application:

enter image description here

My custom button class must extend JButton or BasicButtonUI so that it can be reused.

I did some research on Stack Overflow, but I did not understand the answers, especially with the time restraints from my boss.


Solution

  • You should create your own component for this.

    Override the paintComponent method on a JPanel, and inside the paintComponent method draw (ie fill) a rounded rectangle2D in the color gray :

    RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(x, y, w, h, 10, 10);
    g.fill(roundedRectangle);
    

    (The last two values determine the curvature. Play around until you get what you want)

    Now move the x,y and reduce width and height so that when you draw the next rectangle, it sits inside the gray rectangle. Set the graphics color to blue then do something like this :

    RoundRectangle2D roundedRectangle2 = new RoundRectangle2D.Float(x + 5, y + 5, w - 10, h - 10, 10, 10);
    g.fill(roundedRectangle2);
    

    You will also need to add text. Adding text requires an x and y position. The exact x and y position can be tricky to calculate, so you may need to use FontMetrics to get some more information about the rectanglar shape of the string. Fontmetrics has methods like stringWidth() and getHeight() which will help you determine what your x and y should be.

    g.drawString("Click Me", x, y);
    

    Finally you need to have a mouse motion listener on your panel. The listener needs to find when the mouse is over the button and then redraw the component.

    Your rectangle can be cast to a shape object, and a calculation can be made as to whether the mouse is in the shape. Eg :

    shape.contains(x,y)
    

    If it contains, change the color, then call repaint() or updateUI() on the panel.

    Note: your color object should be kept as a class level field in the class, so that it can be changed via the mouseover.

    Hope this helps!