Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!