I am showing an error in my main method for this statement: // non-static variable this cannot be referenced from a static context
frame.getContentPane().add(new PieChart());
I thought this would be as easy as loading a content pane and adding the PieChart class to it. I spent several hours today and was hoping I could get help with this issue. I have 10 weeks experience with Java and haven't wandered out of my depth until now. Any advice is greatly appreciated.
Here is my PieChart program:
package iapiechart;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class IAPieChart{
double arcValue; // passes a value for the calculation of the arc.
Color marker; // holds value for color (expressed as an integer
public IAPieChart(double value, Color color){
this.arcValue = value;
this.marker = color;
}
public class PieChart extends JComponent {
IAPieChart[] pieValue = {new IAPieChart(5, Color.green),
new IAPieChart(33, Color.orange),
new IAPieChart(20, Color.blue),
new IAPieChart(15, Color.red)
};
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), pieValue);
}
void drawPie(Graphics2D g, Rectangle area, IAPieChart[] pieValue){
double sum = 0.0D;
for (int i = 0; i < pieValue.length; i++) {
sum += pieValue[i].arcValue;
}
double endPoint = 0.0D;
int arcStart = 0;
for (int i = 0; i < pieValue.length; i++){
endPoint = (int) (endPoint * 360 / sum);
int radius = (int) (pieValue[i].arcValue * 360/ sum);
g.setColor(pieValue[i].marker);
g.fillArc(area.x, area.y, area.width, area.height, arcStart, radius);
radius += pieValue[i].arcValue;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new PieChart()); // This is where the error occurs.
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}