4

Pedi ajuda sobre como pintar um botão com 3 cores diferentes: É possível colocar 3 cores em um botão?

Porém estou tentando trocar a cor dele em tempo de execução e não consigo. Mesmo instanciando um novo e substituindo.

A classe do botão é esta:

 class MultiColorButton extends JButton {
    Graphics g ;
    public MultiColorButton() {
        setContentAreaFilled(false);

    }
    @Override
    protected void paintComponent(Graphics g) {
        this.g = g;
          int fractionWitdh = 0;     
            fractionWitdh = getWidth();
             g.setColor(Color.GRAY);
             g.fillRect(0, 0, fractionWitdh, getHeight());
        super.paintComponent(g);

    }

    void newcolor()
    {

         int fractionWitdh = getWidth()/3;

        g.setColor(new Color(63, 72, 204));
        g.fillRect(0, 0, fractionWitdh, getHeight());

        g.setColor(new Color(181, 230, 29));
        g.fillRect(fractionWitdh, 0, fractionWitdh, getHeight());

        g.setColor(new Color(237, 28, 36));
        g.fillRect(fractionWitdh * 2, 0, fractionWitdh, getHeight());
        super.repaint();
        super.paintComponent(g);

    }
}

o Método newcolor() seria para pintar o botão com novas cores.

Instancio o botão e o coloco em um vetor:

  Botoes[l][c] = new MultiColorButton();

Adiciono ele da seguinte forma:

 getContentPane().add(Botoes[l][c]);

Depois tento trocar sua Cor da seguinte forma,porém sem êxito.

           Botoes[i][c].newcolor();
           Botoes[i][c].repaint();

Não sei o que está faltando,pois esse é o meu primeiro contato com paint no java.

1 Resposta 1

5

Edit.: Otimizei a classe para que não fique limitada a apenas 3 cores, mas a quantidade que você achar necessário.


Basta criar um método na classe MultiColorButton que receba o array de cores(ou as 3 cores individuais), atribui-las a um array de cores e forçar o repaint() do botão logo após atribuir as cores no array:

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) {

        int colorsCount = colors.length;

        if (colorsCount > 0) {

            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);
    }
}

Para ilustrar a forma de uso, fiz esse exemplo que gera cores randômicas para o botão, cada vez que ele é clicado:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.multi.MultiRootPaneUI;
import javax.swing.JButton;
import java.awt.Dimension;

public class JButtonMultipleColorsTest extends JFrame {

    private JPanel contentPane;
    private JPanel panel;
    private MultiColorButton multiColorButton;
    private GradientButton gradientButton;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JButtonMultipleColorsTest frame = new JButtonMultipleColorsTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public JButtonMultipleColorsTest() {
        initComponents();
        pack();
        setLocationRelativeTo(null);
    }

    private void initComponents() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(300, 200));
        this.contentPane = new JPanel();
        this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        this.contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(this.contentPane);

        this.panel = new JPanel();
        this.contentPane.add(this.panel, BorderLayout.CENTER);

        this.multiColorButton = new MultiColorButton();
        this.multiColorButton.addActionListener(e -> {

            Random rand =  new Random();

            Color[] colors =  new Color[3];

            for(int i = 0; i < colors.length; i++)
                colors[i] = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));

            multiColorButton.setColors(colors);
        });
        this.multiColorButton.setText("multicolor btn");
        this.panel.add(this.multiColorButton);
    }
    class MultiColorButton extends JButton implements iColorsButton {

        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);
        }
    }
}

Veja funcionando:

inserir a descrição da imagem aqui

1
  • Agora vi Onde errei,Obrigado pela atenção e pelo código bem didático !
    – saidmrn
    8/10/2017 às 19:06

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .