So I am trying to figure out why my GUI isn't drawing and coloring my shapes.
Basically, I have to draw and color various shapes. Shapes are generated upon pressing a JButton on the GUI and stored in a List. However, I am unable to draw each shape. I changed the implementation inside of paintComponent so that it would iterate over my list of shapes.
I believe my problem lies within this class, which is responsible for creating the GUI, making the shapes, and painting them:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MyPanel extends JPanel{
private List<Shape> shapes = new ArrayList<Shape>();
final int SIZE = 6;
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
for (Shape shape: shapes) {
g2d.setColor(shape.getColor());
shape.drawShape(g2d);
}
}
public static void main (String[] args) {
JButton loading = new JButton("Load shapes");
JPanel panel = new JPanel();
JFrame frame = new JFrame("Display shapes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
loading.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
new MyPanel().generateAllShapes();
}
});
panel.add(loading);
}
public void generateAllShapes() {
shapes = new ArrayList<Shape>();
ShapeFactory sf = new ShapeFactory();
for (int i = 0; i < SIZE; i++) {
shapes.add(sf.generateShape());
}
sf.spaceShapes(shapes);
}
}
This is my drawShape method in one of my other classes:
@Override
public void drawShape(Graphics form) {
// TODO Auto-generated method stub
form.drawRect(upperX, upperY, width, length);
form.fillRect(upperX, upperY, width, length);
I omitted the other classes but they are just basic implementations of various shape classes as well as the abstract Shape class they extend from. I have a simple ShapeFactory class which just basically generates a random shape as well as a random color for it.