所以我无法将框架居中以使我的整个图表都在屏幕上。目前,当我运行我的程序时,坐标系上的 x 值是正确的范围,但我几乎看不到我的图形,因为框架位于图形绘制位置上方数百像素的中心。这是我的代码:
public static int startx = 1;
public static int endx = 500;
static Scanner input = new Scanner(System.in);
int WIDTH = 0;
int HEIGHT = 0;
public GraphSigma(int WIDTH, int HEIGHT) {
this.WIDTH = WIDTH;
this.HEIGHT = HEIGHT;
}
// Draw your spiral here!!!
// You'll need to use a FOR loop to calculate the
// points on the spiral
public void paintSigma(Graphics g){
int prevX=startx;
int prevY=Sigma.Sigma(startx);
Graphics2D g2 = (Graphics2D) g;
g2.translate(0, Sigma.Sigma(endx));
g2.scale(1,-1);
if (endx-startx < 50)
for (int i = startx; i <= endx; i++) {
int x = i;
int y = Sigma.Sigma(i);
g.drawLine(0+prevX, 0+prevY, x, y);
prevX=x;
prevY=y;
};
if (51 < endx-startx && endx-startx < 300)
for (int i = startx; i <= endx; i+=2) {
int x = i;
int y = Sigma.Sigma(i);
g.drawLine(0+prevX, 0+prevY, x, y);
prevX=x;
prevY=y;
};
if (301 < endx-startx && endx-startx < 1000)
for (int i = startx; i <= endx; i+=4) {
int x = i;
int y = Sigma.Sigma(i);
g.drawLine(0+prevX, 0+prevY, x, y);
prevX=x;
prevY=y;
};
if (1000<endx-startx)
for (int i = startx; i <= endx; i+=10) {
int x = i;
int y = Sigma.Sigma(i);
g.drawLine(0+prevX, 0+prevY, x, y);
prevX=x;
prevY=y;
};
}
// This special method is automatically called when the scene needs to be drawn.
public void paintComponent(Graphics g) {
paintSigma(g);
}
public static void main(String[] args) {
// Graphics window size
int WINDOW_WIDTH = endx-startx+20;
int WINDOW_HEIGHT = endx;
JFrame frame = new JFrame();
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setTitle("Sigma Function");
GraphSigma d = new GraphSigma(endx-startx+20, Sigma.Sigma(endx));
frame.add(d);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我调用的 sigma 方法在不同的类中,这里是它的代码: public class Sigma {
static Scanner input = new Scanner(System.in);
public static int Sigma(int s){
int a = 0;
for(int i=1;i<=s;i++){
if(s%i==0)
a = a + i;
}
return a;
}
public static void main(String[] args) {
System.out.println("Please enter the number you want to perform the sigma function on");
int s = input.nextInt();
System.out.print(Sigma.Sigma(s) +" is the sum of all the divisors of your input" );
}
}
老实说,我不知道如何正确地将其居中,我是否缺少方法?我一直在弄乱变量,它们似乎并没有改变框架的居中方式。非常感谢!