我真的被卡住了。我似乎无法弄清楚为什么我paintComponent
的前一种颜色会不断变换颜色。我认为问题出在我的arraylist
,但我不知道如何更改arraylist
以便它可以接受不同种类的颜色。
public class Drawing extends JPanel {
private JRadioButton red, yellow, blue, erase;
private JButton button;
private Color c;
private ArrayList<Point> pointList;
private int counter = 0;
private boolean isDrawingMode = true;
private boolean eraser, isBlue;
private HashMap test;
public Drawing() {
setLayout(new FlowLayout());
setBackground(Color.white);
JPanel pane = new JPanel();
pointList = new ArrayList<Point>();
addMouseListener(new MouseTrackerListener());
red = new JRadioButton("Red");
yellow = new JRadioButton("Yellow");
blue = new JRadioButton("Blue");
erase = new JRadioButton("Erase");
button = new JButton("Clear Drawing");
red.addActionListener(new ColorActionListener());
yellow.addActionListener(new ColorActionListener());
blue.addActionListener(new ColorActionListener());
erase.addActionListener(new ColorActionListener());
button.addActionListener(new ColorActionListener());
pane.add(red);
pane.add(yellow);
pane.add(blue);
pane.add(erase);
pane.add(button);
add(pane);
pane.setBackground(Color.gray);
ButtonGroup group = new ButtonGroup();
group.add(red);
group.add(yellow);
group.add(blue);
group.add(erase);
setPreferredSize(new Dimension(500, 500));
}
public void paintComponent(Graphics pen) {
super.paintComponent(pen);
pen.setColor(Color.red);
pen.setColor(c);
for (int i = 0; i < pointList.size(); i++) {
Point p = pointList.get(i);
pen.fillOval(p.x, p.y, 10, 10);
if (eraser = true) {
p = pointList.get(i);
pen.drawOval(p.x, p.y, 10, 10);
}
}
}
private class MouseTrackerListener extends MouseInputAdapter {
public void mouseClicked(MouseEvent e) {
counter++;
if (counter % 2 != 0) {
addMouseMotionListener(new MouseTrackerListener());
isDrawingMode = true;
} else {
isDrawingMode = false;
}
}
public void mouseMoved(MouseEvent e) {
if (isDrawingMode) {
Point point = e.getPoint();
pointList.add(point);
repaint();
}
}
}
private class ColorActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == red) {
c = Color.red;
} else if (e.getSource() == yellow) {
c = Color.yellow;
} else if (e.getSource() == blue) {
isBlue=true;
c = Color.blue;
} else if (e.getSource() == erase) {
eraser = true;
c=Color.white;
} else if (e.getSource() == button) {
pointList.clear();
repaint();
}
}
}
public static void main(String[] args) {
Drawing draw = new Drawing();
JFrame frame = new JFrame("Draw Something!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(draw);
frame.setSize(450, 450);
frame.setVisible(true);
}
}