I am in an entry level Java class and am supposed to implement 3 classes, ItalianFlag, ItalianFlagViewer and ItalianFlagComponent and use as much object oriented design as possible so one can specify the coordinates x and y and width to draw the Italian flag. I am supposed to test the design by drawing two flags in my viewer.
My problem is that I have the Italian Flag designed, but cannot get it to appear twice on my viewer. I'll post my codes in hopes someone can point out my flaw. I am actually happy I got this far...
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; public class ItalianFlagComponent extends JComponent{ public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; ItalianFlag flag1 = new ItalianFlag(0,0,0, Color.black); ItalianFlag flag2 = new ItalianFlag(200, 200, 200, Color.black); flag1.draw(g2); flag2.draw(g2); } }
import java.awt.geom.*; import java.awt.*; public class ItalianFlag { public int x,y; public Color c; public ItalianFlag(double x, double y, double aWidth) { } public ItalianFlag(double x, double y, double aWidth, Color c){ this.c= c; } public void draw(Graphics2D g2) { Rectangle leftRectangle = new Rectangle(x+15, y+10, 45, 45); Rectangle rightRectangle = new Rectangle (x+100, y+10, 45, 45); Point2D.Double r1= new Point2D.Double(x+15, y+10); Point2D.Double r2= new Point2D.Double(x+100, y+10); Line2D.Double top= new Line2D.Double(r1,r2); Point2D.Double r3= new Point2D.Double(x+45, y+55); Point2D.Double r4= new Point2D.Double(x+115, y+55); Line2D.Double bottom= new Line2D.Double(r3,r4); g2.setColor(Color.GREEN); g2.fill(leftRectangle); g2.setColor(Color.RED); g2.fill(rightRectangle); g2.setColor(c); g2.draw(leftRectangle); g2.draw(rightRectangle); g2.draw(top); g2.draw(bottom); } }
import javax.swing.*; public class ItalianFlagViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ItalianFlagComponent component = new ItalianFlagComponent(); frame.add(component); frame.setVisible(true); } }
I hope that's not too jumbled, I'm not sure how to clearly post codes where they are easily readable.
Thanks,
Brandon