This is my first time drawing in Java. this is what I have so far. I am not sure
ID: 3558249 • Letter: T
Question
This is my first time drawing in Java. this is what I have so far. I am not sure how to use the for loops to make the windows or how to randomize the colors when it is repainted.
package labBuilding;
import java.awt.Graphics;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Building extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(100, 100, 400, 600);
// TODO: write code to draw the building
}
}
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(200, 50, 600, 800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new Building());
setVisible(true);
}
}
Description:
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.
Explanation / Answer
If the objective is to paint every shape with a random color then you'd have to update graphics color for every shape that is drawn. Ie:
for (Rectangle2D r : arrOfRect) {
g.setColor(getRandomColor());
g2.draw(r);
}
There is no need to allocate new Random in every call, you can make it a private member. For example:
private Random randomNumber = new Random();
private Color getRandomColor() {
return new Color(randomNumber.nextFloat(),
randomNumber.nextFloat(), randomNumber.nextFloat());
}
If you want to assign a random color to each shape in add() method and keep it then you'd have to maintain a map of colors, or some other structure that serves the goal.
Other minor but important notes:
Don't forget to call super.paintComponent() inside your implementation of paintComponent.
Do not call repaint() in paintComponent(), as it eventually triggers paintComponent. So you're creating unnecessary repaints.
Do call repaint() inside add() to repaint the component with a newly created shape.
See Performing Custom Painting for more details and examples.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.