Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda