Share on Google+Share on Google+

Create Round Button in Java swing

Advertisement
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:

Advertisements

Posted on: September 19, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.