In: Computer Science
I want to update this JAVA program to : Exit cleanly, and change the pie chart to circle rather than an oval, and provide a separate driver please and thank you
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Scanner;
import javax.swing.JComponent;
import javax.swing.JFrame;
// class to store the value and color mapping of the
// pie segment(slices)
class Segment {
double value;
Color color;
// constructor
public Segment(double value, Color color) {
this.value = value;
this.color = color;
}
}
class pieChartComponent extends JComponent {
private static final long serialVersionUID = 1L;
Segment[] Segments;
// Parameterized constructor
// create 4 segments of the pie chart
pieChartComponent(int v1, int v2, int v3, int v4) {
Segments = new Segment[] { new Segment(v1, Color.black), new
Segment(v2, Color.green), new Segment(v3, Color.yellow),
new Segment(v4, Color.red) };
}
// function responsible for calling the worker method
drawPie
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), Segments);
}
// worker function for creating the percentage wise slices of
the pie chart
void drawPie(Graphics2D g, Rectangle area, Segment[] Segments)
{
double total = 0.0D;
// fin the total of the all the inputs provided by the user
for (int i = 0; i < Segments.length; i++) {
total += Segments[i].value;
}
// Initialization
double curValue = 0.0D;
int strtAngle = 0;
// iterate till all the segments are covered
for (int i = 0; i < Segments.length; i++) {
// compute start angle, with percentage
strtAngle = (int) (curValue * 360 / total);
// find the area angle of the segment
int arcAngle = (int) (Segments[i].value * 360 / total);
g.setColor(Segments[i].color);
g.fillArc(area.x, area.y, area.width, area.height, strtAngle,
arcAngle);
curValue += Segments[i].value;
}
}
}
public class Graphic_Pie2D {
public static void main(String[] argv) {
System.out.println("Pleae provide 4 values, to create the pie
chart");
Scanner input = new Scanner(System.in);
int v1, v2, v3, v4;
v1 = input.nextInt();
v2 = input.nextInt();
v3 = input.nextInt();
v4 = input.nextInt();
// create a JFrame with title
JFrame frame = new JFrame("Pie Chart");
frame.getContentPane().add(new
pieChartComponent(v1,v2,v3,v4));
frame.setSize(500, 300);
frame.setVisible(true);
}
}
here's the assignment for reference :
Pie chart: prompt the user (at the command line) for 4 positive integers, then draw a pie chart in a window. Convert the numbers to percentages of the numbers’ total sum; color each segment differently; use Arc2D. No text fields (other than the window title) are required. Provide a driver in a separate source file to test your class.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class PieChartApplet extends Applet implements ActionListener {
PieChartCanvas chart; // A canvas that displays the pie chart.
TextField[] inputs; // Input boxes where the user enters the data.
Label message; // Label for displaying message to the user.
public void init() {
// Initialize the applet.
setBackground(Color.darkGray); // Color for borders and gaps.
setLayout(new BorderLayout(2,2)); // The main layout is a BorderLayout.
/* The South position of the main BorderLayout is occupied by
a Panel that contains the message label and two buttons.
This panel also uses a BorderLayout. The message label
occupies the Center position and the Buttons occupy the
East and West positions. The applet listens for ActionEvents
from the buttons.
*/
Panel bottom = new Panel();
add(bottom, BorderLayout.SOUTH);
bottom.setLayout(new BorderLayout(2,2));
message = new Label("Enter your data and click here: ", Label.CENTER);
message.setBackground(Color.lightGray);
bottom.add(message, BorderLayout.CENTER);
Button make = new Button("Make Chart");
make.addActionListener(this);
make.setBackground(Color.lightGray);
bottom.add(make, BorderLayout.EAST);
Button clear = new Button("Clear");
clear.addActionListener(this);
clear.setBackground(Color.lightGray);
bottom.add(clear, BorderLayout.WEST);
/* The Center position of the main BorderLayout is occupied by
a Panel that contains the input boxes and the PieChartCanvas.
This Panel uses a GridLayout that divides it horizontally into
two pieces. The left half is occupied by another Panel that
holds the input boxes. The right half is occupied by the chart.
*/
Panel top = new Panel();
add(top, BorderLayout.CENTER);
top.setLayout(new GridLayout(1,2,2,2));
Panel left = new Panel(); // Panel to hold 12 input boxes in a grid.
top.add(left);
left.setLayout(new GridLayout(6,2,2,2));
inputs = new TextField[12]; // Make an array to hold the input boxes.
for (int i = 0; i < 12; i++) {
inputs[i] = new TextField(); // Create the i-th input box.
inputs[i].setBackground(Color.white);
left.add(inputs[i]);
}
chart = new PieChartCanvas();
top.add(chart);
} // add init();
public Insets getInsets() {
// Specify a 2-pixel border around the edges of the applet.
return new Insets(2,2,2,2);
}
public void actionPerformed(ActionEvent evt) {
// This is called when the user clicks on one of the two buttons.
// Call another subroutine to handle the action.
String cmd = evt.getActionCommand();
if (cmd.equals("Clear"))
doClear();
else if (cmd.equals("Make Chart"))
doChart();
}
void doClear() {
// Called by actionPerformed() when the user clicks the "Clear"
// button. Empty all the TextFields, and clear the pie chart.
// Reset the message label, in case it was showing an error message.
chart.clearData();
message.setText("Enter your data and click here: ");
for (int i = 0; i < 12; i++)
inputs[i].setText("");
inputs[0].requestFocus();
}
void doChart() {
// Called by actionPerformedI() when the user clicks the "Make Chart"
// button. Get up to 12 data values form the 12 input boxes. Ignore
// any empty boxes and zeros. If illegal data is found, show a message
// and exit. Otherwise, tell the PieChartCanvas to draw a pie chart
// for the data. (If an error is found, clear the current pie chart
// so the user will notice that something is wrong.)
double[] data = new double[12]; // An array to hold the data.
int dataCt = 0; // Number of data items found (ignoring empty boxes).
for (int i = 0; i < 12; i++) {
// Try to get data from the i-th input box.
String numStr; // The contents of the i-th box, as a string.
double num; // The contents of the i-th box, as a number.
numStr = inputs[i].getText().trim();
if (numStr.length() > 0) {
try {
// Try to convert the string to a numerical value.
Double d = new Double(numStr);
num = d.doubleValue();
}
catch (NumberFormatException e) {
// The data in box i is not a legal number.
message.setText("Invalid number input " + i);
inputs[i].selectAll();
inputs[i].requestFocus();
chart.clearData();
return;
}
if (num < 0) {
// The data in box i is a negative number.
message.setText("Negative numbers not allowed.");
inputs[i].selectAll();
inputs[i].requestFocus();
chart.clearData();
return;
}
if (num > 0) {
// Put the number in the data array, but only if it
// is positive. Zero values are ignored.
data[dataCt] = num;
dataCt++;
}
} // end if
} // end for
if (dataCt == 0) {
// No positive numbers were found.
message.setText("Please enter some data!");
inputs[0].requestFocus();
chart.clearData();
return;
}
/* Reset the message label, in case it was showing an error message. */
message.setText("Enter your data and click here: ");
/* Tell the PieChartCanvas to draw a pie chart with the new data. */
chart.setData(data,dataCt);
} // end doChart()
} // end PieChartApplet
class PieChartCanvas extends Canvas {
// A PieChartCanvas can display a pie chart, based on an array
// of data passed to it in its setData() method. There can be
// up to 12 wedges in the pie.
private int dataCt; // The number of data values for the chart.
private int[] angles; // An array to hold the angles that divide
// the wedges. For convenience, this array
// is of size dataCt + 1, and it starts with
// 0 and ends with 360.
private final static Color[] palette = { // Colors for the chart.
Color.red,
Color.blue,
Color.green,
Color.magenta,
Color.yellow,
Color.cyan,
new Color(180,0,0),
new Color(200,200,255),
new Color(0,180,0),
new Color(0,180,180),
new Color(180,180,0),
new Color(180,0,180),
};
PieChartCanvas() {
// Constructor. Set the background to be white.
setBackground(Color.white);
}
void clearData() {
// Delete any data and redraw the canvas. The canvas will
// be blank except for the message "No data available".
dataCt = 0;
angles = null;
repaint();
}
void setData(double[] data, int count) {
// Use data and count for the pie chart. If data is null or
// count is <= 0, the current pie chart will be cleared.
// The count must be in the range 0 to data.length. If not, it
// is set to data.length. All the entries in the array should
// be positive numbers. If not, the results will be nonsense.
// The data needed to draw the pie chart is computed and stored
// in the angles array. Note that the number of degrees
// in the i-th wedge is 360*data[i]/dataSum, where dataSum
// is the total of all the data values. The cumulative angles
// are computed, converted to ints, and stored in angles.
if (count <= 0 || data == null) {
clearData();
}
else {
if (count <= data.length)
dataCt = count;
else
dataCt = data.length;
angles = new int[dataCt + 1];
angles[0] = 0;
angles[dataCt] = 360;
double dataSum = 0;
for (int i = 0; i < dataCt; i++)
dataSum += data[i];
double sum = 0;
for (int i = 1; i < dataCt; i++) {
sum += data[i-1];
angles[i] = (int)(360*sum/dataSum + 0.5);
}
repaint();
}
} // end setData()
public void paint(Graphics g) {
// Draw the pie chart, if there is data available.
// If not, just show the message "No data available".
if (dataCt == 0) {
g.drawString("No data available.", 10,15);
return;
}
/* The pie chart occupies a circle centered on the canvas.
Compute some parameters for drawing it.
*/
int centerX = getSize().width / 2; // Center point of circle.
int centerY = getSize().height / 2;
int radius; // Radius of the circle. This is 20 pixels less
// than the smaller of half the width and
// half the height.
if (centerX < centerY)
radius = centerX - 20;
else
radius = centerY - 20;
int top = centerY - radius; // Top edge of square
// that contains the circle.
int left = centerX - radius; // Left edge of square
// that contains the circle.
int diameter = 2*radius; // Length of a side of the square.
for (int i = 0; i < dataCt; i++) {
// Draw the next wedge. The start angle for the wedge
// is angles[i]. The ending angle is angles[i+1}, so
// the number of degrees in the wedge is
// angles[i+1] - angles[i].
g.setColor( palette[i] );
g.fillArc( left, top, diameter, diameter,
angles[i], angles[i+1] - angles[i] ) ;
}
} // end paint()
} // end PieChartCanvas