I have to do the following steps:
1) Project6 class will have to extend the JFrame class
2) Project6 constructor will have to set up the GUI window.
3) A new abstract method: public void display(Graphics g); should be added to the base and derived classes
4) A custom JPanel must be set up with a paintComponent method (see project 3)
5) The new display(Graphics g) method will have to draw the shapes on the GUI window and be called from a loop in the paintComponent method
I've done pretty much everything and the GUI window will pop up with the title "Shapes" and the size/location that I've specified. Except, I cannot get the array of shapes to show in the GUI window.
Here is the code:
package project6;
import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Project6 extends JFrame{
private static Shape [] thearray = new Shape[100]; // 100 Shapes, circle's, tri's and rects
static MyPanel panel;
public static void main (String [] args) {
Project6 tpo = new Project6();
tpo.run();
} // end of main
public void run () {
int count = 0;
// ------------------------ Fill the array section ----------------------
thearray[count++] = new Circle(-4, 20, 40);
thearray[count++] = new Circle(900, 120, 40);
thearray[count++] = new Circle(220, 220, 40);
thearray[count++] = new Triangle(70, 70, 20, 30);
thearray[count++] = new Triangle(170, 170, 20, 30);
thearray[count++] = new Triangle(270, 270, 20, 30);
// ------------------------------ array fill done ------------------------
//--------------------------- loop through the array --------------------
for (int i = 0; i < count; i ++ ) { // loop through all objects in the array
thearray[i].display(); // don’t care what kind of object, display it
} // end for loop
int offset = 0;
double totalarea = 0.0;
while (thearray[offset] != null) { // loop through all objects in the array
totalarea = totalarea + thearray[offset].area(); // get area for this object
offset++;
} // end while loop
System.out.println("The total area for " + offset + " Shape objects is " + totalarea);
} // end of run
//Project6 constructor w/out parameters to set up new JFrame
public Project6(){
JFrame frame= new JFrame("Shapes");
frame.setSize(900, 700);
frame.setBackground (Color.WHITE);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
frame.setVisible(true);
}
public static class MyPanel extends JPanel {
public static JPanel showJPanel(Graphics g){
panel=new MyPanel();
return panel;
}
@Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
for (int i = 0; i < thearray.length && thearray[i] !=null; i ++ )
thearray[i].display();
} // end of paintComponent
} // end of MyPanel
} // end of class Project6