PLEASE code using JAVA (UML included!!!) Project: Displaying Regular Polygons Pr
ID: 669234 • Letter: P
Question
PLEASE code using JAVA (UML included!!!)
Project: Displaying Regular Polygons
Problem Description:
Create a subclass of JPanel, named RegularPolygonPanel, to paint an n-sided regular polygon. The class contains a property named numberOfSides, which specifies the number of sides in the polygon. The polygon is centered at the center of the panel. The size of the polygon is proportional to the size of the panel. Create a pentagon, hexagon, heptagon, and octagon, nonagon, and decagon from RegularPolygonPanel and display them in a frame, as shown in the figure below.
Your Task:
1.Create a class named RegularPolygonPanel to paint an n-sided regular polygon. (So, if n is 3, it paints a triangle, if n is 4, it paints a square, etc.)
2.Create a frame class that contains pentagon, hexagon, heptagon, and octagon, nonagon, and decagon. These objects are created from RegularPolygonPanel.
3.Draw a UML diagram for the RegularPolygonPanel class and the frame class.
Exercise15 25Explanation / Answer
RegularPolygonPanel.class
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class RegularPolygonPanel extends JPanel {
public static int N=5;
RegularPolygonPanel(int side){
N = side;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getBounds().width;
int h = getBounds().height;
//the circle of such radius will nicely fit the panel
double r = Math.min(h, w)/2.0*0.9;
Point[] vert = new Point[N];
for(int i=0;i<N;i++){
vert[i]=new Point((int)(r*Math.cos(2*Math.PI*i/N)+w/2),(int)(h/2-r*Math.sin(2*Math.PI*i/N)));
}
for(int i=0;i<N;i++){
Point p1 = vert[i];
Point p2 = vert[(i+1)%N];
g.drawLine(p1.x, p1.y, p2.x,p2.y);
}
}
}
frame.class
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class frame extends JFrame {
frame() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.pack();
frame.setBounds(20, 100, 400, 200);
// pass different value for different polygon
int polygon = 7;
frame.add(new RegularPolygonPanel(polygon));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame f = new frame();
}
});
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.