1

I am trying to create a custom JButton that will look like this: Custom JButton Here is my code, where I override JButton and abstract border:

class PolygonButton extends JButton {
     public PolygonButton(String value) {
         super(value);
     }
     Polygon polygon;

     @Override
     public boolean contains(int x, int y) {
        int width = getSize().width;
        int height = getSize().height;
        int xPoints[] = { width / 5, width, width, width - width / 5, 0, 0, width / 5 };
        int yPoints[] = { 0, 0, height - height / 5, height, height, height / 5, 0 };
        if (polygon == null || !polygon.getBounds().equals(getBounds())) {
            polygon = new Polygon(xPoints, yPoints, xPoints.length);
        }
        return polygon.contains(x, y);
    }
}

Code where I override abstract border:

class CustomBorder extends AbstractBorder {
    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    super.paintBorder(c, g, x, y, width, height);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.WHITE);
    int xPoints[] = { width / 5, width, width, width - width/5, 0, 0 };
    int yPoints[] = { 0, 0, height - height/5, height, height, height/5 };
    g2d.draw(new Polygon(xPoints, yPoints, xPoints.length));
    }
}

What I end up with is button that has the right contains but the border, while having the general form of the desired border, is cut off at the top and left and is super thin.

Is there a better way to tackle a custom border where I would end up with a JButton with the same look as image above and have a variable border thickness?

RomanK
  • 155
  • 1
  • 2
  • 13
  • Possible duplicate [Java Swing drawing PlayButton for a basic music player](https://stackoverflow.com/questions/44384073/java-swing-drawing-playbutton-for-a-basic-music-player/44404175#44404175) and [Swing: Create a UWP (“Metro”)–like button](https://stackoverflow.com/questions/46448044/swing-create-a-uwp-metro-like-button/46458112#46458112) and [Why .paintComponent() is defined on JComponent?](https://stackoverflow.com/questions/47339013/why-paintcomponent-is-defined-on-jcomponent/47341727#47341727) – MadProgrammer Apr 04 '18 at 04:21
  • Take a look at the linked questions. You may also take a look [here](http://esus.com/creating-a-rounded-jbutton/) or [here](https://java-swing-tips.blogspot.gr/2008/07/create-round-image-jbutton.html). – gthanop Apr 04 '18 at 12:02

0 Answers0