Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

mport javax.swing.JPanel; import java.awt.*; public class RegularPolygonPanel ex

ID: 3637846 • Letter: M

Question

mport javax.swing.JPanel;
import java.awt.*;

public class RegularPolygonPanel extends JPanel {
private int numberOfSides = 3;

public RegularPolygonPanel() {
}

public RegularPolygonPanel(int numberOfSides) {
setNumberOfSides(numberOfSides);
}

public int getNumberOfSides() {
return numberOfSides;
}

public void setNumberOfSides(int numberOfSides) {
this.numberOfSides = numberOfSides;
repaint();
}

protected void paintComponent(Graphics g) {
super.paintComponent(g);

int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius =
(int) (Math.min(getWidth(), getHeight()) * 0.4);

double angle = 2 * Math.PI / numberOfSides;

// Create a Polygon object
Polygon polygon = new Polygon();

// Add points to the polygon
for (int i = 0; i < numberOfSides; i++) {
polygon.addPoint((int)(xCenter + radius * Math.cos(i * angle)),
(int)(yCenter - radius * Math.sin(i * angle)));
}

/**
polygon.addPoint(xCenter + radius, yCenter);
polygon.addPoint((int)(xCenter + radius * Math.cos(1 * angle)),
(int)(yCenter - radius * Math.sin(angle)));
polygon.addPoint((int)(xCenter + radius * Math.cos(2 * angle)),
(int)(yCenter - radius * Math.sin(2 * angle)));
polygon.addPoint((int)(xCenter + radius * Math.cos(3 * angle)),
(int)(yCenter - radius * Math.sin(3 * angle)));
polygon.addPoint((int)(xCenter + radius * Math.cos(4 * angle)),
(int)(yCenter - radius * Math.sin(4 * angle)));
polygon.addPoint((int)(xCenter + radius * Math.cos(5 * angle)),
(int)(yCenter - radius * Math.sin(5 * angle)));
polygon.addPoint((int)(xCenter + radius * Math.cos(6 * angle)),
(int)(yCenter - radius * Math.sin(6 * angle)));
polygon.addPoint((int)(xCenter + radius * Math.cos(7 * angle)),
(int)(yCenter - radius * Math.sin(7 * angle)));
*/
// Draw the polygon
g.drawPolygon(polygon);
}

public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

Write a program to this code, which is RegularPolygonPanel for displaying an n-sided polygon. The program should display a regular polygon and uses two buttons named +1 and -1 to increase or decrease the size of the polygon.

Explanation / Answer

public class ListLetters { /* This program reads a line of text entered by the user. It prints a list of the letters that occur in the text, and it reports how many different letters were found. */ public static void main(String[] args) { String str; // Line of text entered by the user. int count; // Number of different letters found in str. char letter; // A letter of the alphabet. TextIO.putln("Please type in a line of text."); str = TextIO.getln(); str = str.toUpperCase(); count = 0; TextIO.putln("Your input contains the following letters:"); TextIO.putln(); TextIO.put(" "); for ( letter = 'A'; letter