How to create a method in a Jbuttons Array that changes the color of jButton with Actionperformed?

Asked

Viewed 774 times

4

I am doing a project that requires the creation of a pencil tool that will paint a group of jButtons positioned in gridLayout (10x10) as if they were pixels.

I created a method called 'colorButton' to change the color of JButton according to the tool (pencil or bucket) and the color of the selected pencil (there are another 10 jButtons colors that determine the color ), it is necessary to choose the tool and the color and then the pixel (jButton) which will be painted.

For this I created two global variables that are changed according to the type of tool (pencil or paint bucket) and color (10 different colors) selected, called type and color.

The problem occurs that instead of calling a ActionPerformed for each of the 100 jButtons of gridLayout to apply the 'colorButton' method, I have created a new method for creating the 100 jButtons for the 'colorButton' method to be applied to each of them, however I need this method to be applied only if the jButton is clicked, that is, it has the same effect as the ActionPerformed.

Below is an excerpt of my code

public class ColorirRegioesGraficas extends javax.swing.JFrame {

/**
 * Creates new form ColorirRegioesGraficas
 */
public ColorirRegioesGraficas() {
    initComponents();

}
//Método que cria os 100 jButtons dentro de um panel e atribui o método de cor para cada um deles.

public void criaPixel(){ 
    JButton[] button = new JButton[100];

    for (int i = 0; i < 100; i++){
    button[i] = new JButton();       
    pnlPixels.add(button[i]);
    colorButton(button[i]);         
    }       
}
//Método de cor que altera a cor de um jButton de acordo com a cor selecionada.

public void colorButton(JButton button){ 
    if (tipo.equals("lapis")){ //Preciso de algo que funcione como um if(button.actionPerformed.isTrue)
        switch (cor) {
            case "cinza":
                button.setBackground( new Color(101,101,101));
                break;
            case "branco":
                button.setBackground( new Color(255,255,255));
                break;
            case "preto":
                button.setBackground( new Color(0,0,0));
                break;
            case "azulE":
                button.setBackground( new Color(0,0,255));
                break;
            case "vermelho":
                button.setBackground( new Color(255,0,0));
                break;
            case "verde":
                button.setBackground( new Color(0,204,0));
                break;
            case "amarelo":
                button.setBackground( new Color(255,255,0));
                break;
            case "laranja":
                button.setBackground( new Color(255,204,0));
                break;
            case "rosa":
                button.setBackground( new Color(255,153,153));
                break;
            case "azulC":
                button.setBackground( new Color(0,204,204));
                break;
            default:
                break;
        }
    }
}

String cor; // É determinada ao clicar em um dos jButtons coloridos
String tipo; // É determinado ao clicar em um dos jButtons com ferramentas

In this case, you would play the call from the Ixel() method within each jButton color, because the variables color and type would already be defined and the method would work properly, but I need to know how to verify if the button was clicked to apply the colorButton method.

1 answer

1


From what I understand, all you have to do is create a class that implements ActionListener, and assign to all buttons. The class could be like this:

class AcaoBotaoColoridoListener implements ActionListener {

 @Override
 public void actionPerformed(ActionEvent e) {
  JButton button = (JButton) e.getSource();
  if ("lapis".equals(tipo)) { 
   switch (cor) {
    case "cinza":
     button.setBackground(new Color(101, 101, 101));
     break;
    case "branco":
     button.setBackground(new Color(255, 255, 255));
     break;
    case "preto":
     button.setBackground(new Color(0, 0, 0));
     break;
    case "azulE":
     button.setBackground(new Color(0, 0, 255));
     break;
    case "vermelho":
     button.setBackground(new Color(255, 0, 0));
     break;
    case "verde":
     button.setBackground(new Color(0, 204, 0));
     break;
    case "amarelo":
     button.setBackground(new Color(255, 255, 0));
     break;
    case "laranja":
     button.setBackground(new Color(255, 204, 0));
     break;
    case "rosa":
     button.setBackground(new Color(255, 153, 153));
     break;
    case "azulC":
     button.setBackground(new Color(0, 204, 204));
     break;
    default:
     break;
   }
  }
 }
}

Then just apply to each button, using the same loop you already use to create the buttons:

JButton[] button = new JButton[100];

for (int i = 0; i < 100; i++){
button[i] = new JButton();       
pnlPixels.add(button[i]);
button[i].addActionListener(new AcaoBotaoColoridoListener());         
} 

Obs.: inverti the comparison of your if to "lapis".equals(tipo), so, if tipo Reach null, avoid problems with Nullpointerexception in Strings comparisons.


Updating

There is a more "elegant" way to do this, which is by using Map to save the colors, so you don’t need to make a swith...case with so much choice.

First create a variable of type Map where the key will be the string with the color names, and the value will be the colors themselves:

private Map<String, Color> colorMap;

(...)

colorMap = new HashMap<String, Color>();
colorMap.put("cinza", new Color(101, 101, 101));
colorMap.put("branco", new Color(255, 255, 255));
colorMap.put("preto", new Color(0, 0, 0));
colorMap.put("azulE", new Color(0, 0, 255));
colorMap.put("vermelho", new Color(255, 0, 0));
colorMap.put("verde", new Color(0, 204, 0));
colorMap.put("amarelho", new Color(255, 255, 0));
colorMap.put("laranja", new Color(255, 204, 0));
colorMap.put("rosa", new Color(255, 153, 153));
colorMap.put("azulC", new Color(0, 204, 204));

Then just check if the color exists in the Map and set the color for the button. See how the class looked:

class AcaoBotaoColoridoListener implements ActionListener {

    private Map<String, Color> colorMap;

    public AcaoBotaoColoridoListener() {

        colorMap = new HashMap<String, Color>();
        colorMap.put("cinza", new Color(101, 101, 101));
        colorMap.put("branco", new Color(255, 255, 255));
        colorMap.put("preto", new Color(0, 0, 0));
        colorMap.put("azulE", new Color(0, 0, 255));
        colorMap.put("vermelho", new Color(255, 0, 0));
        colorMap.put("verde", new Color(0, 204, 0));
        colorMap.put("amarelho", new Color(255, 255, 0));
        colorMap.put("laranja", new Color(255, 204, 0));
        colorMap.put("rosa", new Color(255, 153, 153));
        colorMap.put("azulC", new Color(0, 204, 204));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton) e.getSource();
        if ("lapis".equals(tipo) && colorMap.containsKey(cor)) {
            button.setBackground(colorMap.get(cor));
        }
    }
}

Note that the code has now become more readable and easier to maintain.

  • I created the class and applied in the same way as shown, but occurred error "Cannot find Symbol" in AcaoBotaoColoridoListener() inside the button creation loop. ;private ActionListener AcaoBotaoColoridoListener() {&#xA; throw new UnsupportedOperationException("Not supported yet.");

  • @Devikn edited, said a New there in the.

  • 1

    Perfect friend! There was no attack on the small detail of new. With its properly implemented class I removed the call from the method criaPixel of each jButton colored and put again next to the initialization of the project, because now the variables will not be null being made the comparisons of the global variables only after the actionPerformed of each jButton be triggered, which will occur only after the variables have received the equivalent Strings. It worked as desired, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.