Question
I wrote the code for an etch-a-sketch program and it runs great; however, I am running into a problem when I draw my lines. So
I wrote the code for an etch-a-sketch program and it runs great; however, I am running into a problem when I draw my lines. So if you let off the mouse after dragging a line segment, then come back and drag another segment, it joins the new segment to where the previous segment left off, and I want it to not do that. I just need help altering my code so that does not happen anymore. Here is my code:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class Etch_A_Sketch implements MouseListener, MouseMotionListener { JFrame window; Container contentPane; int mouseX, mouseY, oldX, oldY; JLabel coords; Color currDrawingColor = Color.BLACK; Color colors[] = new Color[4]; int currentColor; JButton button;
public Etch_A_Sketch() { JFrame window = new JFrame("Classic Etch a Sketch"); contentPane = window.getContentPane(); contentPane.setLayout(new FlowLayout()); coords = new JLabel(); coords.setFont(new Font("TimesRoman", Font.ITALIC + Font.BOLD, 32)); button = new JButton(); button.setText("Change Color"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setRandomColor(); } }); contentPane.add(coords); contentPane.add(button); contentPane.addMouseListener(this); contentPane.addMouseMotionListener(this); window.setSize(640, 480); window.setVisible(true);
currentColor = 0; colors[0] = Color.BLACK; colors[1] = Color.RED; colors[2] = Color.BLUE; colors[3] = Color.YELLOW; contentPane.getGraphics().setColor(colors[currentColor]); }
public void mouseClicked(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); }
public void mousePressed(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); }
public void mouseReleased(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); }
public void mouseExited(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); }
public void mouseEntered(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); }
void setRandomColor() { currentColor++; currentColor = currentColor%4; }
public void mouseDragged(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY();
if (oldX == 0) { oldX = mouseX; oldY = mouseY; return; }
Graphics g = contentPane.getGraphics(); g.setColor(colors[currentColor]); g.drawLine(oldX, oldY, mouseX, mouseY); oldX = mouseX; oldY = mouseY; }
public void mouseMoved(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); }
public static void main(String[] args) { new Etch_A_Sketch(); }
private void reportEventCoords(String msg) { coords.setText(msg); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started