Is it possible to put 3 colors on a button?

9

I need to divide the button into 3 "equal pieces" and each piece has a different color.  For example, a button with the colors Blue, Green and Red, each occupying 33.3% of space. How to do this?

    
asked by anonymous 08.10.2017 / 04:41

1 answer

15
  

Edit : I've optimized the two classes so that they are not limited to just 3 colors, but the amount that you find necessary.

Without using a gradient, applying color splitting exactly as you exemplified:

class MultiColorButton extends JButton {

    private static final long serialVersionUID = 1L;
    Color[] colors;

    public MultiColorButton() {
        this(new Color[] { new Color(63, 72, 204), new Color(181, 230, 29), new Color(237, 28, 36) });
    }

    public MultiColorButton(Color[] colors) {
        setContentAreaFilled(false);
        setFocusPainted(false);
        this.setColors(colors);
    }

    public void setColors(Color[] colors) {
        this.colors = colors;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {

        if (colors != null && colors.length > 0) {

            int colorsCount = colors.length;
            int fractionWitdh = getWidth() / colorsCount;

            for (int i = 0; i < colorsCount; i++) {
                g.setColor(colors[i]);
                g.fillRect(fractionWitdh * i, 0, fractionWitdh, getHeight());
            }
        }
        super.paintComponent(g);
    }
}

Result:

Althoughitwasnotmentionedinthequestion,Ileaveherealineargradientalternative,whichmakesthecolortransitionmorebeautiful:

classGradientButtonextendsJButton{privatestaticfinallongserialVersionUID=1L;Color[]colors;publicGradientButton(){this(newColor[]{newColor(63,72,204),newColor(181,230,29),newColor(237,28,36)});}publicGradientButton(Color[]colors){setContentAreaFilled(false);setFocusPainted(false);this.colors=colors;}@OverridepublicvoidsetColors(Color[]colors){this.colors=colors;repaint();}@OverrideprotectedvoidpaintComponent(Graphicsg){finalGraphics2Dg2d=(Graphics2D)g;float[]fractions=newfloat[colors.length];for(inti=1;i<=fractions.length;i++){floatfraction=1.0f/fractions.length;fractions[i-1]=i*fraction;}g2d.setPaint(newLinearGradientPaint(0,0,getWidth(),getHeight(),fractions,colors));g2d.fillRect(0,0,getWidth(),getHeight());super.paintComponent(g);}}

Result:

Usage is like that of a common JButton.

It's up to you to choose the best option;)

    
08.10.2017 / 09:27