Should I still be practicing Java Swing?
I'm trying to add functionality to my Java Swing Paint Application by adding a choice to change brush colors. However, when I'm finished choosing a different color in the color chooser, all of the old marks change into that chosen color along with my new line marks. I wanted the old marks to stay the same color as before.
(Pictures below)
Using black ink. Drawing something.
Deciding to change the color to green
Both the old AND new lines change to green.
This is not the entire application(tell me if you need the rest), but I believe the problem has something to do with incorrect table manipulation. The "shapeFill" table which matches colors to the lines("shapes" table) is not working correctly.
public class TestPane extends JComponent{
private List<List<Point>> points;
private ArrayList<Shape> shapes = new ArrayList<Shape>();
public TestPane() {
points = new ArrayList<>(100);
MouseAdapter ma = new MouseAdapter() {
private List<Point> currentPath;
@Override
public void mousePressed(MouseEvent e) {
currentPath = new ArrayList<>(100);
currentPath.add(e.getPoint());
points.add(currentPath);
}
@Override
public void mouseDragged(MouseEvent e) {
Point dragPoint = e.getPoint();
currentPath.add(dragPoint);
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
currentPath = null;
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Iterator<Color> fillCounter = shapeFill.iterator();
for(Shape s : shapes) { // I believe problem is somewhere around here?
g2d.setPaint(fillCounter.next());
g2d.setStroke(new java.awt.BasicStroke(10));
}
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (List<Point> path : points) {
Point from = null;
for (Point p : path) {
if (from != null) {
Shape line = new Line2D.Float(from.x, from.y, p.x, p.y);
g2d.draw(line);
shapes.add(line);
shapeFill.add(lineColor);
}
from = p;
}
}
g2d.dispose();
}
}
public JButton createButton(String title) {
JButton button = new JButton(title);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == colorChooser) {
Color chooser = JColorChooser.showDialog(null, "Select color", lineColor);
lineColor = chooser;
shapeFill.add(chooser);
repaint();
}else if(e.getSource() == shapeFillArrayList) {
System.out.print("\n");
for(Color index : shapeFill) {
System.out.println(index);
}
}
}
});
return button;
}