-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTriangleComponent.java
More file actions
93 lines (86 loc) · 1.98 KB
/
TriangleComponent.java
File metadata and controls
93 lines (86 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package cpsc101.nickslugocki.lab6;
/**
* This file is part of a solution to
* CPSC 101, Winter 2020, Lab 6, Problem P10.16
*
* This program sets up the frame for records mouse clicks for up to three points and draws a
* triangle.
* If one points are given, only a point is drawn.
* If two points are given, a line is drawn.
* If three points are given, a triangle is drawn.
* The points reset after 3 clicks.
*
* This class represents the Java Swing Component for our program's GUI elements.
*
* @author Nicholas Slugocki
* Student Number: 230082267
* @version 1
*/
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import javax.swing.JComponent;
public class TriangleComponent extends JComponent
{
private static final int MAXPOINTS = 3;
private int[] xValues = new int[MAXPOINTS];
private int[] yValues = new int[MAXPOINTS];
private int pointsRecorded = 0;
private Polygon polygon = new Polygon();
@Override
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(polygon);
}
/**
* Records a point at the given x and y values.
* @param x x-value
* @param y y-value
* @return Nothing
*/
public void recordPoint(int x, int y)
{
if (pointsRecorded == MAXPOINTS) {
resetPoints();
}
xValues[pointsRecorded] = x;
yValues[pointsRecorded] = y;
pointsRecorded++;
}
/**
* Resets the list of recorded points.
* @return Nothing
*/
public void resetPoints()
{
for (int i = 0; i < MAXPOINTS; i++)
{
xValues[i] = 0;
yValues[i] = 0;
pointsRecorded = 0;
}
}
/**
* Draws up to three points. A single point will result in just a point. Two points will draw
* a line. Three points draws a triangle.
* @return Nothing
*/
public void drawPoints()
{
if (pointsRecorded == 1)
{
int x = xValues[0];
int y = yValues[0];
polygon = new Polygon();
polygon.addPoint(x, y);
polygon.addPoint(x, y + 1);
repaint();
}
else
{
polygon = new Polygon(xValues, yValues, pointsRecorded);
repaint();
}
}
}