You should get something like this:
Object | X | Y | Width | Height |
---|---|---|---|---|
House | 50 | 100 | 150 | 100 |
Door | 120 | 150 | 20 | 50 |
Left Window | 75 | 140 | 25 | 40 |
Right Window | 160 | 140 | 25 | 40 |
Tree Trunk | 260 | 65 | 10 | 100 |
With this information,
you can start coding.
The code starts by defining
variables that contain the above coordinates.
Give the variables names that show their use.
For example houseX
is the X coordinate
of the left edge of the house.
houseW
is the width of the house.
You may think that it would be just as easy to put the numbers directly
into the drawRect()
calls.
But if you need to make adjustments later on,
it is very useful to have
names for the various values you wish to change.
import javax.swing.*; import java.awt.*; class HousePanel extends JPanel { final int width = 350, height = 250; final int houseX = 50, houseY = 100, houseW = 150, houseH = 100 ; final int doorX = 120, doorY = 150, doorW = 20, doorH = 50 ; final int lWindX = 75, lWindY = 140, lWindW = 25, lWindH = 40 ; final int rWindX = 160, rWindY = 140, rWindW = 25, rWindH = 40 ; final int trunkX = , trunkY = , trunkW = , trunkH = ; public HousePanel() { setPreferredSize( new Dimension( width, height) ); setBackground( Color.WHITE); } public void paintComponent ( Graphics gr ) { super.paintComponent( gr ); gr.setColor( Color.ORANGE ); // there is no Color brown gr.drawRect( houseX , houseY , houseW, houseH); // house gr.drawRect( doorX , doorY , doorW , doorH ); // door gr.drawRect( lWindX , lWindY , lWindW, lWindH); // lwind gr.drawRect( rWindX , rWindY , rWindW, rWindH); // rwind gr.drawRect( , , , ); // trunk } } public class HouseRectangles { public static void main ( String[] args ) { JFrame frame = new JFrame( "House Picture: Rectangles" ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.getContentPane().add( new HousePanel() ); frame.pack(); // Adjust the frame size to match the JPanel frame.setVisible( true ); } }
Fill in the blanks. (Look at the table for the values, then copy variable names into drawRect()
.)