简体   繁体   中英

Painting on JLabel - change brush color

I am working on a tool that requires painting on the Icon of a Label. That works fine so far, but if I change the color of the brush, all the already-painted lines also change color.

This is my overridden paintComponent method:

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(brushColor);
        g2.setStroke(brush);
        for (int i = 1; i < point.size(); i++) {
            g2.draw(new Line2D.Float(point.get(i), point.get(i)));
        }
    }

Here's how to change my brush color:

    public void changeBrushColor(int red, int green, int blue) {
        this.brushRed = red;
        this.brushGreen = green;
        this.brushBlue = blue;

        brushColor = new Color(red, green, blue);
        this.brush = new BasicStroke(brushWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
    }

And this is how I add points to the point-Array:

        imageLabel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent event) {
                updateBrush();
                point.add(event.getPoint());
                imageLabel.updatePointList(point);
                repaint();
            }
        });

        imageLabel.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent event) {
                updateBrush();
                point.add(event.getPoint());
                imageLabel.updatePointList(point);
                repaint();
            }
        });

Well, you misunderstood how drawing in a JLabel or the corresponding Graphics -object works.

There are no "already painted" lines on your JLabel , since the Graphics -object will be erased. The paintComponent() will draw all lines anew.

In your code you set the color for all lines before drawing.

What you have to do is to store the line color together with your points and change the color when drawing a single line.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    for (int i = 1; i < point.size(); i++) {
        g2.setColor(colors.get(i));
        g2.setStroke(brushes.get(i));
        g2.draw(new Line2D.Float(point.get(i).x, point.get(i).y));
    }
}

Well here you need 3 lists, one for color, one for brush and one for points. Maybe you consider to create an object which capsules these values (eg " Linedesc(color, brush, point) ") to only have a list containing them (" point = new ArrayList<LineDesc>() ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM