Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Need help with the point tracer in Java. I am using IntelliJ. import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; import java.util.List; import java.util.concurrent.*; import
Need help with the point tracer in Java. I am using IntelliJ.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; import java.util.List; import java.util.concurrent.*; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.Timer; /** * The main Display class for the picture drawing assignment in 152. * * Displays points at user specified locations, with oldest points * fading away. */ public class Display { /** Default length of the trace */ private static final int DEFAULT_TRACE_LENGTH = 25; /** Default point size */ private static final int DEFAULT_POINT_SIZE = 5; /** Maximum fps for the speed slider */ private static final int MAX_FPS = 200; /** * Special class for drawing dots on a display */ private class DisplayPanel extends JPanel { /** * Default constructor sets up default behavior */ public DisplayPanel() { setPreferredSize(new Dimension(400, 400)); setBackground(Color.BLACK); } public void paintComponent(Graphics g) { super.paintComponent(g); IteratorcolorListIterator = colors.subList( colors.size() - points.size(), colors.size()).iterator(); int offset = -pointSize / 2; synchronized (points) { Iterator pointIterator = points.iterator(); while (pointIterator.hasNext()) { if (colorListIterator.hasNext()) { g.setColor(colorListIterator.next()); } Point p = pointIterator.next(); g.fillRect(p.x + offset, p.y + offset, pointSize, pointSize); } } } } /** * List of points */ private List points = null; /** * List of colors */ private List colors = null; /** * Current trace index */ private int maxTraceLength = DEFAULT_TRACE_LENGTH; /** * Frames per second to use for the update frequency */ private int fps = MAX_FPS / 4; /** Timer to draw one point per tick */ private Timer timer = new Timer(1000 / fps, event -> doDrawNextPoint()); /** Points to process as timer ticks */ private BlockingQueue pointsToProcess = new ArrayBlockingQueue(DEFAULT_TRACE_LENGTH); /** * Starting color of the first point */ private Color pointColor = Color.RED; /** * Size of each point to draw */ private int pointSize = DEFAULT_POINT_SIZE; /** * Panel to draw points on */ private DisplayPanel drawPanel; /** * Construct display with default trace length and point size. */ public Display() { this(DEFAULT_TRACE_LENGTH, DEFAULT_POINT_SIZE); } /** * Main constructor for the display * @param traceLength The number of trace points to use * @param pointSize The size of each box point */ public Display(int traceLength, int pointSize) { setTraceLength(traceLength); JFrame mainFrame = new JFrame(); mainFrame.setSize(450, 450); mainFrame.setTitle("CS152 Point Tracer"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel control = new JPanel(); control.setPreferredSize(new Dimension(400, 50)); control.add(new JLabel("Speed:")); // Create the speed slider to control update frequency JSlider speedSlider = new JSlider(); speedSlider.setPreferredSize(new Dimension(75, 20)); speedSlider.setCursor(new Cursor(Cursor.HAND_CURSOR)); speedSlider.setMaximum(MAX_FPS); speedSlider.setMinimum(1); speedSlider.setPaintTicks(false); speedSlider.setValue(fps); speedSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider s = (JSlider) e.getSource(); fps = s.getValue(); timer.setDelay(1000 / fps); } }); control.add(speedSlider); control.add(new JLabel("Length:")); JTextField lengthField = new JTextField(); lengthField.setPreferredSize(new Dimension(50, 20)); lengthField.setText("" + maxTraceLength); lengthField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JTextField jtf = (JTextField) e.getSource(); int length = maxTraceLength; try { length = Integer.parseInt(jtf.getText()); setTraceLength(length); } catch (NumberFormatException ex) { jtf.setText("" + length); } } }); control.add(lengthField); // Create a button that allows user to pick a new color to draw with final JButton colorButton = new JButton("Color"); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Color chosenColor = JColorChooser.showDialog(colorButton, "Pick a color", pointColor); if (chosenColor != null) { pointColor = chosenColor; } generateColorSpectrum(); } }); control.add(colorButton); // Create the quit button so we can exit JButton quitButton = new JButton("Quit"); quitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); control.add(quitButton); // Add the control panel to the main frame mainFrame.add(control, BorderLayout.SOUTH); // Create the JPanel that we will draw the points on drawPanel = new DisplayPanel(); mainFrame.add(drawPanel, BorderLayout.CENTER); if (pointSize = maxTraceLength) { points.remove(0); } points.add(point); drawPanel.repaint(); } /** * Return the height of the black part of the display * @return Panel height. */ public int getHeight() { return drawPanel.getHeight(); } /** * Return the width of the black part of the display * @return Panel width. */ public int getWidth() { return drawPanel.getWidth(); } /** * Return String representation of this Display object * @return String for the display. */ public String toString() { return "point display ( " + getWidth() + " by " + getHeight() + ")"; } /** * After updates of the color or size of spectrum, this method is called to * create the new set of colors to use when drawing */ private void generateColorSpectrum() { // Generate new color spectrum colors = Collections.synchronizedList(new LinkedList ()); float alphaDiff = 1.0f / maxTraceLength; float red = pointColor.getRed() / 255f; float green = pointColor.getGreen() / 255f; float blue = pointColor.getBlue() / 255f; for (int i = maxTraceLength - 1; i >= 0; i--) { colors.add(new Color(red, green, blue, 1.0f - alphaDiff * i)); } } /** * Update the length of the point trace * @param length length of the trace, > 1 */ private void setTraceLength(int length) { // Set the new trace length maxTraceLength = length ()); } else if (maxTraceLength In this assignment, you will write a program that uses a class I have provided for you to draw a picture or pattern of points. 1 The Display class The Display class is a small little class. Its only function is to display points. The window keeps track of the last n points that were displayed and draws them as a trace of fading color. - When creating the display window object, we will specify the number of trailing points and the size in pixels of each point. For example, to create a Display object that will display a trace of fifty points, each five pixels wide, and assign it to a variable named "window", you would write following line of code. Displaywindow=newDisplay(50,5); - To draw a point at a particular position, you will use the drawPointAt method. The coordinate system we use has (0,0) at the upper left corner, with x increasing as we go to the right and y increasing as we go down. For example, if we were using the Display variable above, we could draw a point at (25,40) with the following line of code. window. drawPointAt (25,40); - I've also provided you with two other methods to tell you how many pixels wide and how tall the display area is. Again using the Display variable above, we can query the display size and assign the values to variables, like so. int width = window getwidth (); int height = window getHeight (); To use the Display class, you need to place Display.java in the src directory of your IntelliJ project along with the java file for the program that is using it. I have given you a couple example programs so you can try it out. 2 What you have to do 1. Create a class named PointTracer. 2. Create a Display object in the main method. You should only create one Display object for the entire program. 3. Call the drawPointAt method with a coordinate of (200,200) and run your program. A point should be drawn at the center of the screen. Try calling drawPointAt with other coordinates to see what happens. What happens if you put the method call inside a loop? 4. Now that you've started your program, change it to draw the following in succession. - Box - Make the display window draw a point that moves around the screen to create a square. This means that you will have to modify the indices of the point to move right, then down, then left, and then up. You will need to use several loops for this. You may draw the box whereever you like and of whatever size you choose as long as it fits on the window and the point is shown moving around the perimeter of the square in a continuous path. - Spiral - I gave you an example of code that drew points on the circumference of a circle, where the angle was changing each iteration of the loop, but the radius was fixed. Consider what happens if you also change the radius. You'll draw a spiral. Write a single loop that will draw a spiral shape on the same display that you used for the box. It is up to you whether it is drawn from the outside in or the center out, but either way, you do need to stop spiralling at some point. See the mathematical explanations in section 3, if you are feeling rusty on your trig functions and need a little help understanding the math in my circle demo code. - Something Fancy - Come up with your own "fancy" version of a moving point. The idea should be more complex than the movement on the circle - Can you come up with some nifty pattern? 1 Again, draw this third part on the same display as the first two parts. Make sure that the loops for your box and spiral designs eventually terminate so the graders will be able to see all three parts of your program. The fancy third part can 3 Circle trigonometry Calculating the x and y coordinates for a point p on a circle as described in the figure below, is not too complicated if we use a little trigonometry. Bascially, referring to the figure, we can calculate: x=rcosy=rsin The trignometric methods in the java Math class, expects angles measured in radians, so if you are used to thinking of angles as degrees, you may want to convert those degrees to coordinates before applying the sin and cos methods. The Figure 1: The measureconversion is simple: rads =180degs. Even better, the Math ments of a circle class has handy toRadians and toDegrees methods you can used to convert back and forth. 4 Turning in your assignment Submit your PointTracer.java file to the Lab 3 assignment in Canvas. Do not attach . class files or any other files. Only submit one file, a single program that draws all three required parts
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