Is it possible to change the shape of a JButton/Button to be triangular?

Davanum Srinivas

Here's a sample based on JDC Tech Tips, August 26, 1999

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

public class TriangleButton extends JButton {
  public TriangleButton(String label) {

    // These statements enlarge the button so that it 
    // becomes a circle rather than an oval.
    Dimension size = getPreferredSize();
    size.width = size.height = Math.max(size.width, 

    // This call causes the JButton not to paint 
    // the background.
    // This allows us to paint a round background.

  // Paint the round background and label.
  protected void paintComponent(Graphics g) {
    if (getModel().isArmed()) {
      // You might want to make the highlight color 
      // a property of the RoundButton class.
    } else {
    int x3Points[] = {getSize().width/2, 0, getSize().width};
    int y3Points[] = {0, getSize().height, getSize().height};
    g.fillPolygon(x3Points, y3Points, x3Points.length); 

    // This call will paint the label and the 
    // focus rectangle.

  // Paint the border of the button using a simple stroke.
  protected void paintBorder(Graphics g) {
    int x3Points[] = {getSize().width/2, 0, getSize().width};
    int y3Points[] = {0, getSize().height, getSize().height};
    g.drawPolygon(x3Points, y3Points, x3Points.length); 

  // Hit detection.
  Polygon polygon;
  public boolean contains(int x, int y) {
    // If the button has changed size, 
    // make a new shape object.
    if (polygon == null || 
      !polygon.getBounds().equals(getBounds())) {
      int x3Points[] = {getSize().width/2, 0, getSize().width};
      int y3Points[] = {0, getSize().height, getSize().height};
      polygon = new Polygon(x3Points,y3Points,3);
    return polygon.contains(x, y);

  // Test routine.
  public static void main(String[] args) {
    // Create a button with the label "Jackpot".
    JButton button = new TriangleButton("Jackpot");

    // Create a frame in which to show the button.
    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setSize(150, 150);
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.