8
Edit.: I optimized the two classes so that they are not limited to only 3 colors, but the amount you find necessary.
Without using gradient, applying the color division 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);
}
}
Upshot:
Although not mentioned in the question, I leave here an alternative with linear gradient, which makes the transition of colors more beautiful:
class GradientButton extends JButton {
private static final long serialVersionUID = 1L;
Color[] colors;
public GradientButton() {
this(new Color[] { new Color(63, 72, 204), new Color(181, 230, 29), new Color(237, 28, 36) });
}
public GradientButton(Color[] colors) {
setContentAreaFilled(false);
setFocusPainted(false);
this.colors = colors;
}
@Override
public void setColors(Color[] colors) {
this.colors = colors;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
final Graphics2D g2d = (Graphics2D) g;
float[] fractions = new float[colors.length];
for (int i = 1; i <= fractions.length; i++) {
float fraction = 1.0f / fractions.length;
fractions[i - 1] = i * fraction;
}
g2d.setPaint(new LinearGradientPaint(0, 0, getWidth(), getHeight(), fractions, colors));
g2d.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
}
Upshot:
The use is like that of a common Jbutton.
Your choice is the best option ;)
Place an image with the colors in the background
– WMomesso