java的简单绘图
java简单绘图
import javax.swing.*;
import java.awt.*;
public class Main extends JPanel {
private static final int N = 10;
private static final double P = 0.34;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int width = getWidth();
int height = getHeight();
int xOffset = width / 2;
int yOffset = height / 2;
g2d.setColor(Color.black);
g2d.drawLine(50,height-50,width-50,height-50);
g2d.drawLine(width-60,height-60,width-50,height-50);
g2d.drawLine(width-60,height-40,width-50,height-50);
g2d.drawLine(40,60,50,50);
g2d.drawLine(60,60,50,50);
g2d.drawLine(50,50,50,height-50);
g2d.drawString("次数n",width-60,height-20);
g2d.drawString("期望E",10,50);
double ex=N*P;
int jg=(width-50)/20;
for(int i=0;i<19;i++){
g2d.drawLine(50+i*jg,height-45,50+i*jg,height-55);
String kb=String.format("%d",i);
int fontwidth=g2d.getFontMetrics().stringWidth(kb)/2;
g2d.drawString(kb,50+i*jg-fontwidth, height-20);
}
jg=(height-50)/20;
for(int i=0;i<19;i++){
g2d.drawLine(45,height-50-i*jg,55,height-50-i*jg);
double kbb=0.2+i*0.01;
String kb=String.format("%.2f",kbb);
int fontwidth=g2d.getFontMetrics().stringWidth(kb);
int fontheight=g2d.getFontMetrics().getHeight()/3;
g2d.drawString(kb,40-fontwidth,height-50-i*jg+fontheight);
}
g2d.setStroke(new BasicStroke(5));
g2d.setColor(Color.cyan);
g2d.fillRect(50+10*(width-50)/20-6,height-50-14*(height-50)/20+6,5,5);
Stroke dash = new BasicStroke(2.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 3.5f, new float[] { 15, 10, }, 0f);
g2d.setColor(Color.yellow);
g2d.setStroke(dash);
g2d.drawLine(50+10*(width-50)/20-6,height-50-14*(height-50)/20+20,50+10*(width-50)/20-6,height-55);
g2d.drawLine(50+10*(width-50)/20-20,height-50-14*(height-50)/20+6,50,height-50-14*(height-50)/20+6);
System.out.println("期望: 0.34");
}
private double binomialProbability(int n, int k, double p) {
return combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k);
}
private long combination(int n, int k) {
if (k == 0 || k == n) {
return 1;
}
if (k > n - k) {
k = n - k;
}
long result = 1;
for (int i = 1; i <= k; i++) {
result *= (n - i + 1);
result /= i;
}
return result;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Binomial Distribution Graph");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.add(new Main());
frame.setVisible(true);
}
}