How to create a JButton extension with rounded corners?

青春壹個敷衍的年華 提交于 2019-12-01 10:38:36

I think you've got 2 choices here:

1.Implement drawing yourself in a paint method of your component

2.Create new ButtonUI for your look and feel. In this case i would suggest to use Synch LAF

In both cases drawing different states is your resposibility

The best implementation I have seen of rounded buttons in Swing are in the Substance look and feel:

https://substance.dev.java.net/

Not all themes have rounded buttons so you may need to change the defaults in the demo. The project is open source so it might be worth poking around in the code for some ideas.

I needed to make this as well, this is what I ended up with (Metal LAF only!)

@Override
    protected void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        Shape firstClip = g.getClip();
        RoundRectangle2D rect = new RoundRectangle2D.Double();
        double arc = Math.ceil(getSize().getHeight()/3);
        rect.setRoundRect(0, 0, Math.ceil(getSize().getWidth()), Math.ceil(getSize().getHeight()), arc, arc);
        Area secondClip = new Area(getBounds());
        secondClip.subtract(new Area(rect));
        Area finalClip = new Area(firstClip);
        finalClip.subtract(secondClip);
        g2.setClip(finalClip);
        super.paintComponent(g2);
        Color[] gradients;
        if(getModel().isRollover())
        {
            gradients = new Color[] { new Color(184, 207, 229), new Color(122, 138, 153), new Color(184, 207, 229) };
        }
        else
        {
            gradients = new Color[] { new Color(122, 138, 153) };
        }
        for(int i = 0; i < gradients.length; i++)
        {
            arc -= 2;
            g2.setColor(gradients[i]);
            g2.drawRoundRect(i+1, i+1, (int)Math.ceil(getSize().getWidth()-2)-(i*2), (int)Math.ceil(getSize().getHeight()-2)-(i*2), (int)arc, (int)arc);
        }
    }

Which looks like this: http://i.stack.imgur.com/unZuc.png

You have to care it by yourself:

  • first of all you can catch every kind of action that is used on the button to change the state (like in the code, where mouseIn is used to change a color)
  • then you have to care about every single paint detail you need, for example for gradients you should point to class GradientPaint that is used to draw gradients..

By the way mind that you have to take care of various look-and-feels and that your solution will fit just one of these..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!