Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am having difficulty doing the following Implement the overridden method paint

ID: 3667093 • Letter: I

Question

I am having difficulty doing the following

Implement the overridden method paintComponent so that it paints a tall building with multiple rows of windows.

Requirements:

1.Use for loops to draw the windows.

2.Use random colors (every time the building is repainted some of the colors change randomly. Which of the areas change is up to you.

with this code:

package labBuilding;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class BuildingApp extends JFrame {

   public static void main(String[] args) {
       new BuildingApp().run();
   }
  
   public void run() {
       setBounds(100, 10, 400, 500);
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   add(new Building());
   setVisible(true);
   }

}

import java.awt.Graphics;

import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Building extends JPanel {
  
   @Override
   protected void paintComponent(Graphics g) {
       super.paintComponent(g);
      
       // TODO: write code to draw the building
      
   }

}

Explanation / Answer


// header files
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class BuildingApp extends JFrame
{

   public static void main(String[] args)
   {
       new BuildingApp().run();
   }
  
   // call defined run function
   public void run()
   {
       setBounds(100, 10, 400, 700);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(new Building());
        setVisible(true);
   }

}


Building.java

//header files
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Building extends JPanel
{
   private final Color[] colors = {Color.YELLOW, Color.BLACK};
   private final Random rand = new Random();
   @Override
   protected void paintComponent(Graphics g)
   {
       super.paintComponent(g);
       setBackground(Color.CYAN);
      
       g.setColor(Color.GREEN);
       g.fillRect(0, 600, 400, 100);
       g.setColor(Color.YELLOW);
       g.fillOval(340, 10, 50, 50);
       g.setColor(Color.GRAY);
       g.fillRect(100, 100, 200, 550);
       g.setColor(Color.DARK_GRAY);
       g.fillRect(175, 575, 50, 75);
      
       g.setColor(Color.CYAN);
       for(int i = 0; i < 9; i++)
       {
           for(int j = 0; j < 4 ;j++)
           {
               g.setColor(colors[rand.nextInt(colors.length)]);
              
               g.fillRect(63 + (j+1)*50, 63 + (i+1)*50, 25, 25);
               g.setColor(Color.DARK_GRAY);
               g.fillRect(75 + (j+1)*50, 63 + (i+1)*50, 2, 25);
               g.fillRect(63 + (j+1)*50, 75 + (i+1)*50, 25, 2);
           }
       }
      
   }

}