Create Round Button in Java swing


 

Create Round Button in Java swing

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

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.

Example:


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

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

    setContentAreaFilled(false);
  }

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

    super.paintComponent(g);
  }

  protected void paintBorder(Graphics g) {
    g.setColor(getForeground());
    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");
    button.setBackground(Color.gray);

    JFrame frame = new JFrame();
    frame.getContentPane().add(button);
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setSize(150, 150);
    frame.setVisible(true);
  }
}

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.

Output:

Ads