Question #104771

write a program to draw a dog house use fillRect for the use, drawLine for the roof (you cant fill it though), fillRect for the door, drawString to print your dogs name over the door

Expert's answer

import javax.swing.*;
import java.awt.*;

public class DogHouse extends JPanel {

    public void paint(Graphics g) {

        Graphics2D graph = (Graphics2D) g;

        /**Coordinates of the window center*/
        int cX = getWidth()/2;
        int cY = getHeight()/2;

        /**The first rectangle is home.*/
        graph.setColor(Color.GRAY);
        graph.fillRect(cX/2,2*cY/3,cX,cY);

        /**The second rectangle is the door.*/
        graph.setColor(Color.decode("#FAEBD7"));
        graph.fillRect(2*cX/3,cY,2*cX/3,3*cY/5);

        /**The roof is drawn in two lines.*/
        graph.setColor(Color.GRAY);
        graph.setStroke(new BasicStroke(5.0f));
        graph.drawLine(cX,cY/4,cX/10,cY);
        graph.drawLine(cX,cY/4,2*cX-cX/10,cY);

        /**The name of the dog is written in the middle above the door.
          *The font size changes as the window size changes.
          */
        String strDogName = "Justin Star Boy";
        graph.setFont(new Font("Veranda", Font.BOLD, cX/15));
        FontMetrics fm = graph.getFontMetrics();

        graph.setColor(Color.decode("#D2691E"));
        graph.drawString(strDogName, (getWidth() - fm.stringWidth(strDogName)) / 2,
                                 (getHeight() - fm.getHeight()) / 2 + fm.getAscent() - cY/6);

    }

    public static void main(String[] args) {
        JFrame fr = new JFrame("Dog House");

        fr.setSize(500, 500);
        fr.setLocationRelativeTo(null);
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        fr.getContentPane().add(new DogHouse());

        fr.setVisible(true);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS