我正在尝试制作一个简单的程序,该程序将通过随机生成的点绘制一条曲线,但是出了点问题,编译器给出了一个错误,我才刚刚开始学习Java,这是第一个任务。我希望你能指出我的错误。这是代码
public class Framey {
private static int fact(int n) {
int fact = 1;
for(int i = 1; i <= n;i++) {
fact *= i;
}
return fact;
}
private static double bernstein(float t,int n,int i) {
return (fact(n)/(fact(i)*fact(n-i)))*Math.pow(1-t,n-i)*Math.pow(t,i);
}
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Framey window = new Framey();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Framey() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setbounds(100,100,450,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getcontentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.LIGHT_GRAY);
panel.setbounds(23,35,250,200);
frame.getcontentPane().add(panel);
JSpinner spinner = new JSpinner();
spinner.setbounds(291,113,30,20);
frame.getcontentPane().add(spinner);
JLabel warning = new JLabel("Value cannot be larger than 8!");
warning.setfont(new Font("Tahoma",Font.BOLD,9));
warning.setbounds(283,144,141,53);
frame.getcontentPane().add(warning);
warning.setVisible(false);
JButton btnNewButton = new JButton("New button");
btnNewButton.addactionListener(new actionListener() {
public void actionPerformed(actionEvent e) {
int pointCount;
pointCount = (int) spinner.getvalue();
if (pointCount>8) {
warning.setVisible(true);
}else {warning.setVisible(false);}
Point[] points = getPoints(pointCount);
drawScene(points);
}
private Point[] getPoints(int pointCount) {
Random val = new Random();
Point[] points = new Point[pointCount];
for(int i=0;i<pointCount;i++) {
points[i].x = val.nextInt(panel.getWidth());
points[i].y =val.nextInt(panel.getHeight());
}
return points;
}
private void drawScene(Point[] points) {
int pWidth = panel.getWidth();
int pHeight = panel.getHeight();
Graphics g = panel.getGraphics();
int pointCount = points.length;
g.setColor(Color.WHITE);
g.fillRect(0,pWidth,pHeight);
if(pointCount>1) {
float t = 0;
while( t<=1) {
g.setColor(Color.DARK_GRAY);
besierCurve(t,points);
t+=0.001;
}
}
};
private void besierCurve(float t,Point[] points) {
Graphics g = panel.getGraphics();
int pointCount = points.length;
double bPoly[] = new double[pointCount];
for(int i =0;i<pointCount;i++) {
bPoly[i] = bernstein(t,pointCount-1,i+1);
}
double sumX = 0;
double sumY = 0;
for(int i=0;i<pointCount;i++) {
sumX += bPoly[i] * points[i].x;
sumY += bPoly[i] * points[i].y;
}
int x,y;
x=(int) Math.round(sumX);
y=(int) Math.round(sumY);
g.drawLine(x,y,x,y);
}
});
bezjeLiikne.Framey $ 2.getPoints(Framey.java:106)处bezjeLiikne.Framey $ 2.actionPerformed(Framey.java:98)处的线程“ AWT-EventQueue-0”中的java.lang.NullPointerException