Simple question yet somewhat complex for me to get it working. I want to get rid of my arraylist because I'm not suppose to use arraylist in my project. Background about my app, it's a polymorphic app with components(shapes) that once its own button is clicked they show on the screen on on top of the other. Hard to explain. I will post a picture of it along with the area where the arraylist is located(piece of the code). The program is fully functional. Thanks again.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ShapeDraw{
public static void main(String[] args){
JFrame frame = new JFrame("My Moving Shapes");
Container contentPane=frame.getContentPane();
contentPane.add(new MyCanvas());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
@SuppressWarnings("serial")
class MyCanvas extends JPanel implements ActionListener, MouseListener, MouseMotionListener {
ArrayList<MyShape> shapes = new ArrayList<MyShape>();
Color currentColor = Color.blue;
public MyCanvas() {
setPreferredSize(new Dimension(400, 300));
JComboBox<String> colorOption = new JComboBox<String>();
colorOption.addItem("Blue");
colorOption.addItem("Magenta");
colorOption.addItem("Red");
colorOption.addActionListener(this);
JButton rectButton = new JButton("Rect");
rectButton.addActionListener(this);
JButton ovalButton = new JButton("Oval");
ovalButton.addActionListener(this);
JButton roundRectButton = new JButton("RoundRect");
roundRectButton.addActionListener(this);
JPanel bottom = new JPanel(); // a Panel to hold the control buttons
bottom.setLayout(new GridLayout(1,4,3,3));
bottom.add(rectButton);
bottom.add(ovalButton);
bottom.add(roundRectButton);
bottom.add(colorOption);
setLayout(new BorderLayout(3,3));
add("South",bottom);
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.gray);
}
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0,0,getSize().width,getSize().height);
int top = shapes.size();
for (int i = 0; i < top; i++) {
MyShape s = (MyShape)shapes.get(i);
s.draw(g);
}
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof JComboBox) {
switch ( ((JComboBox<?>)evt.getSource()).getSelectedIndex() ) {
case 0: currentColor = Color.blue; break;
case 1: currentColor = Color.magenta; break;
case 2: currentColor = Color.red; break;
}
}
else {
String command = evt.getActionCommand();
if (command.equals("Rect"))
addShape(new RectShape());
else if (command.equals("Oval"))
addShape(new OvalShape());
else if (command.equals("RoundRect"))
addShape(new RoundRectShape());
}
}