Home Tutorial Java Swing Create Round Button in Java swing


Share on Google+Share on Google+
Create Round Button in Java swing
Posted on: September 19, 2012 at 12:00 AM
In this tutorial, we are going to create a button of round shape.

Create Round Button in Java swing

In this tutorial, we are going to create a button of round shape.

Java2D APIs and Java Swing make it easy to implement custom-shaped buttons. For this you need to extend your class from JButton class, then add code to set the shape you want to give. Finally override the paintComponent() and paintBorder() methods to render the shape.


import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class CreateRoundButton extends JButton {
  public CreateRoundButton(String label) {
    Dimension size = getPreferredSize();
    size.width = size.height = Math.max(size.width,size.height);


  protected void paintComponent(Graphics g) {
    if (getModel().isArmed()) {
    } else {
    g.fillOval(0, 0, getSize().width-1,getSize().height-1);


  protected void paintBorder(Graphics g) {
    g.drawOval(0, 0, getSize().width-1,     getSize().height-1);

  Shape shape;
  public boolean contains(int x, int y) {
    if (shape == null || 
      !shape.getBounds().equals(getBounds())) {
      shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
    return shape.contains(x, y);

  public static void main(String[] args) {
    JButton button = new CreateRoundButton("Click");

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setSize(150, 150);

Description of Code: In this example, we have created a class, extended from the JButton class to give the shape to the button. We have overridden the method paintComponent() to give color to the background and to set the color of the button using setColor method of Graphics class, and using the fillColor() method, it fills the shape with color. We have also overridden the paintBorder() method to paint the border for the custom button.



Related Tags for Create Round Button in Java swing:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 19, 2012

Recommend the tutorial

Advertisements Advertisements