Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
Miniature Pixel art program using JButtons

I have just recently gotten into Java and am a still a noob. I have created a 9x9 panel of JPanels using a for loop to add the buttons. How would I create an action listener that would allow me to choose different colors that will appear as the background color of the JButton when clicked? I'm trying to make a miniature pixel art program.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

It will look something like this. In this example, [row] and [col] refer to the row and column values of your grid. Be sure to create counter (private static int counter = 0;). or else you will get a bunch of errors. Here is the Code:

JBut[row][col].addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        typeOfButton button = (typeOfButton) e.getSource();
        int row = button.getRow();
        int col = button.getCol();

        counter++;
        if (counter == 1) {
            JBut[row][col].setBackground(Color.RED);
        } 
        else if (counter == 2) {
            JBut[row][col].setBackground(Color.ORANGE);
        } 
        else if (counter == 3) {
            JBut[row][col].setBackground(Color.YELLOW);
        } 
        else if (counter == 4) {
            JBut[row][col].setBackground(Color.GREEN);
        } 
        else if (counter == 5){
            JBut[row][col].setBackground(Color.BLUE);
        } 
        else if (counter == 6){
            JBut[row][col].setBackground(Color.MAGENTA);
        } 
        else {
            JBut[row][col].setBackground(Color.BLACK);
            counter = 0; //makes color cycle repeat, starting with red
        } //end else
    } //end actionPerformed
}); //end ActionListener

Obviously, the simple way to do this would be to put the giant if statement in a new method called determineColor() or something like that.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda