我应该还在练习Java Swing吗?
我正在尝试通过添加更改笔刷颜色的选项来向Java Swing Paint应用程序添加功能。但是,当我在颜色选择器中选择了另一种颜色时,所有旧标记都会与我的新线标记一起变为所选颜色。我希望旧标记保持与以前相同的颜色。
(下面的图片)
Using black ink. Drawing something.
Deciding to change the color to green
Both the old AND new lines change to green.
这不是整个应用程序(如果需要,请告诉我),但是我认为问题与表操作不正确有关。将颜色与线条匹配的“ shapeFill”表(“ shapes”表)无法正常工作。
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;
}