Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5946785
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T16:52:18+00:00 2026-05-22T16:52:18+00:00

i have a program similar to paint. and that i am trying to implement

  • 0

i have a program similar to paint. and that i am trying to implement a change pen color however when i change the color, everything currently drawn is changed to the color RED for example in my program,how can i make it such that it will not repaint everything currently drawn to the currently changed color?Below code will compile and run

Class for the JPanel drawing area

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
//refer to http://jkost.ergoway.gr/jnkjavaconnection/freedraw.html for the algorithm.
public class STDrawingArea extends JPanel {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    ArrayList<Rectangle> dPoint = new ArrayList<Rectangle>();
    Point point = new Point(-1,-1);
    private Color currentColor;

    public STDrawingArea()
    {
         setBorder(BorderFactory.createLineBorder(Color.black));
         setBackground(Color.WHITE);

         addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) 
            {
                dPoint.add(new Rectangle(point.x,point.y,e.getX(),e.getY()));
                point.x = e.getX();
                point.y = e.getY();
                repaint();
            }

             });

         addMouseListener(new MouseAdapter(){
             public void mousePressed(MouseEvent e)
             {
                 System.out.println("mousePressed X: "+e.getX()+"mousePressed Y: "+e.getY());
                 dPoint.add(new Rectangle(e.getX(),e.getY(),-1,-1));
                 point.x = e.getX();
                 point.y = e.getY();
             }
         });

         addMouseListener(new MouseAdapter(){
             public void mouseReleased(MouseEvent e)
             {
                 System.out.println("mouseReleased X: "+e.getX()+"mouseReleased Y: "+e.getY());
                 repaint();
             }
         });
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(700,500);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
       g.setColor(getCurrentColor());
        for (int i=0; i < dPoint.size(); i++) {  
            Rectangle r = dPoint.get(i);
            if (r.width != -1)
            {
              g.drawLine(r.x, r.y, r.width, r.height);  
            }
           }  
            /* Draw current point.*/ 
            g.drawLine(point.x, point.y, point.x, point.y);  
    }

    //set current drawing color
    public void changePenColor(Color color)
    {
        if (color == null)
        setCurrentColor(Color.BLACK);
        else
        setCurrentColor(color);
    }

    //clear drawings method
    public void clearDrawings()
    {
        if(!(dPoint==null))
        {
             dPoint.clear();
             repaint();
        }

    }

    private void setCurrentColor(Color currentColor) {
        this.currentColor = currentColor;
    }

    private Color getCurrentColor() {
        return currentColor;
    }
}

Test main class.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class STTestMain extends JFrame {
    STDrawingArea drawingArea = new STDrawingArea();
    public STTestMain()
    {
        //JFrame settings
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Spelling Trainer");
        setResizable(false);
        setVisible(true);


        //Panel of buttons
        JPanel buttonContainer = new JPanel();
        JButton btnPenColor = new JButton("Red Pen");

        buttonContainer.add(btnPenColor);
        //Drawing Area instantiation


        //Adding things to JFrame
        getContentPane().add(drawingArea);
        getContentPane().add(buttonContainer,BorderLayout.PAGE_END);
        pack();


        //button listener
        btnPenColor.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                drawingArea.changePenColor(Color.RED);
            }
        });
    }


    public static void main(String args[])
    {
        STTestMain test = new STTestMain();
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T16:52:19+00:00Added an answer on May 22, 2026 at 4:52 pm

    One way:

    • Use your ArrayList to draw the current curve as it is being drawn, but
    • Use a BufferedImage to draw your completed curves
    • You would do this on mouseReleased and would draw the current curve to the BufferedImage using the current color.
    • You’ll also need to re-initialize your ArrayList of points after drawing to the BufferedImage.
    • Don’t forget to dispose of the BufferedImage’s Graphics object after you’re done using it.
    • Draw the BufferedImage in your paintComponent method after super.paintComponent but before drawing your current curve.
    • This way when you change the color of your drawing, only the current curve is effected.

    EDIT
    You’ve mentioned in a comment that you’re not familiar with BufferedImage, and are looking for another way. I suppose you could create a class that holds an ArrayList of Points together with a Color, and then on each mouseReleased create an object of this class and add it to an ArrayList in your drawing panel. Then your paintComponent method could iterate through that ArrayList, drawing the list of Points with their associated color, but my gut tells me that you’re an intelligent guy and that you’d pick up on how to use a BufferedImage in no time. I really think it’s the best solution. And if you try it and it flops, show us your code, and we’ll likely be able to help you.

    EDIT 2
    The BufferedImage constructor will need the image width, height and an image type — something I’m not 100% familiar with. I usually use BufferedImage.TYPE_INT_RGB for general purpose drawing, and BufferedImage.TYPE_INT_ARGB for general purpose that needs an alpha too. Then you’ll extract a Graphics object out of the BufferedImage, say getGraphics() if all you need is a Graphics object and not a Graphics2D object. Then when you initialize the BufferedImage in your constructor, fill it with a Color.white, just as you for your JPanel. Then dispose the Graphics object. Then each time you want to draw, you getGraphics, draw with it, just like you do in the paintComponent method, dispose of the Graphics when done, and finally draw the BufferedImage in the paintComponent via the drawImage method.

    EDIT 3
    Example program that doesn’t do quite what you are trying to do but does illustrate use of a BufferedImage with drawing. This program changes the color each time a new path or curve is drawn.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.util.ArrayList;
    import javax.swing.*;
    
    public class STTestSimple {
       private static void createAndShowUI() {
          STDrawPanel drawPanel = new STDrawPanel();
          STMouseAdapter mAdapter = new STMouseAdapter(drawPanel);
          drawPanel.addMouseListener(mAdapter);
          drawPanel.addMouseMotionListener(mAdapter);
    
          JFrame frame = new JFrame("Drawing");
          frame.getContentPane().add(drawPanel);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setResizable(false);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    @SuppressWarnings("serial")
    class STDrawPanel extends JPanel {
       private static final int ST_WIDTH = 700;
       private static final int ST_HEIGHT = 500;
       private static final Color BACKGROUND_COLOR = Color.white;
       private static final float STROKE_WIDTH = 6f;
       private static final Stroke STROKE = new BasicStroke(STROKE_WIDTH,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
       private static final Color[] colors = {Color.black, Color.blue, Color.red,
          Color.green, Color.orange, Color.MAGENTA};
    
       private BufferedImage bImage = new BufferedImage(ST_WIDTH, ST_HEIGHT,
                BufferedImage.TYPE_INT_RGB);
       private Color color = Color.black;
       private ArrayList<Point> points = new ArrayList<Point>();
       private int colorIndex = 0;
    
       public STDrawPanel() {
          Graphics g = bImage.getGraphics();
          g.setColor(BACKGROUND_COLOR);
          g.fillRect(0, 0, ST_WIDTH, ST_HEIGHT);
          g.dispose();
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.drawImage(bImage, 0, 0, null);
          Graphics2D g2 = (Graphics2D) g;
          drawCurve(g2);
       }
    
       private void addCurveToBufferedImage() {
          Graphics2D g2 = bImage.createGraphics();
          drawCurve(g2);
          g2.dispose();
       }
    
       private void drawCurve(Graphics2D g2) {
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                   RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setStroke(STROKE);
          g2.setColor(color);
          if (points != null && points.size() > 1) {
             for (int i = 0; i < points.size() - 1; i++) {
                int x1 = points.get(i).x;
                int y1 = points.get(i).y;
                int x2 = points.get(i + 1).x;
                int y2 = points.get(i + 1).y;
                g2.drawLine(x1, y1, x2, y2);
             }
          }
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(ST_WIDTH, ST_HEIGHT);
       }
    
       public void curveStart(Point point) {
          points.clear();
          points.add(point);
       }
    
       public void curveEnd(Point point) {
          points.add(point);
          addCurveToBufferedImage();
          points.clear();
          repaint();
    
          colorIndex++;
          colorIndex %= colors.length;
          setColor(colors[colorIndex]);
       }
    
       public void curveAdd(Point point) {
          points.add(point);
          repaint();
       }
    
       public void setColor(Color color) {
          this.color = color;
       }
    }
    
    class STMouseAdapter extends MouseAdapter {
       private STDrawPanel drawPanel;
    
       public STMouseAdapter(STDrawPanel drawPanel) {
          this.drawPanel = drawPanel;
       }
    
       @Override
       public void mousePressed(MouseEvent e) {
          drawPanel.curveStart(e.getPoint());
       }
    
       @Override
       public void mouseReleased(MouseEvent e) {
          drawPanel.curveEnd(e.getPoint());
       }
    
       @Override
       public void mouseDragged(MouseEvent e) {
          drawPanel.curveAdd(e.getPoint());
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have program that has a variable that should never change. However, somehow, it
So in my program I have a load of buttons that are really similar,
I have a program that is creating an ItemizedOverlay and a map. Everything works
I have program, that must interact with a console program before my program can
I have program that runs fast enough. I want to see the number of
I have a program that spits out both standard error and standard out, and
I have a program that creates a Windows user account using the NetUserAdd() API
I have a program that uses the mt19937 random number generator from boost::random. I
I have a program that spits out an Excel workbook in Excel 2003 XML
I have a program that monitors debug messages and I have tried using a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.