I´m really in need of some help from you guys. I try to add rectangles to an ArrayList and then loop through the list to draw them all. I'm not sure if I'm using the right approach, but here is my code so far.
Edit: the code does not draw the rectangles that I added to the ArrayList. I don't even know if they are added the right way, or accessed through the for-loop in the right way.
In TestProgram
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JFrame;
public class TestProgram extends JFrame {
private ShapeRectangle rectangle;
public ArrayList<Shapes> list = new ArrayList<Shapes>();
public TestProgram(String title) {
super(title);
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
initComponents();
setSize(500, 700);
setVisible(true);
}
private void initComponents() {
rectangle = new ShapeRectangle();
add(rectangle, BorderLayout.CENTER);
list.add(rectangle);
Graphics g = getGraphics();
for (int i = 0; i < list.size(); i++) {
rectangle.draw(g);
}
}
public static void main(String args[]) {
new TestProgram("Drawing program");
}
}
In class ShapeRectangles:
import java.awt.Graphics;
public class ShapeRectangle extends Shapes {
public ShapeRectangle() {}
@Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
draw(g);
}
@Override
public void draw(Graphics g) {
g.drawLine(20,20,60,60);
g.drawLine(130,30,80,11);
g.drawRect(200,30,20,140);
}
}
In class Shapes:
import java.awt.Graphics;
import javax.swing.JPanel;
public abstract class Shapes extends JPanel {
abstract public void draw(Graphics g);
}