提问者:小点点

getHeight()和getWidth()方法


我写了一个程序,希望它通过使用getWidth()和getHeight()方法显示在屏幕中间,但它出现在左上角。所以我的问题是getWidth()和getHeight()方法不应该获得整个屏幕的宽度和高度吗?

/*
 * This program displays Pascal's Triangle for 8 rows.
 */

import acm.graphics.*;
import acm.program.*;


public class combination extends GraphicsProgram {
    public void run() {
        for(int i = 0; i < NROWS; i++) {
            for (int n = 0; n <= i; n++) {

        add(new GLabel(Combination(i,n), x(i,n), y(i))); //the     coordination and the amount of labels are related to i;

        }       
    }
}

//method that adds labels on the screen.//
private String Combination(int i, int n) { //this method returns a string which   would be added to the screen.//

    return (String.valueOf(i) +","+ String.valueOf(n)); 
    }


//method that set the y coordination for the label//
private double y(int i) {
    double Height = getHeight()/NROWS;
    return i * Height + 9;

}

//method that set the x coordination for the label//
private double x(int i, int n)  {
    double Orgnx = getWidth() / 2;
    double HalfBase = getHeight() / NROWS / Math.sqrt(3);
    double Base = HalfBase * 2;
    return Orgnx - i * HalfBase + n * Base;
    }


/*The program displays 8 rows of pairs of number.*/
private static final int NROWS = 8;

共2个答案

匿名用户

getWidth()/getHeight()在Component中定义,因此它们返回您调用它们的组件的大小(在您的情况下,这将是一个窗口内的组件)。

查看Swing教程http://docs.oracle.com/javase/tutorial/uiswing/components/,了解组件是如何组合成用户界面的。

请注意,“屏幕”不是Swing对象,“屏幕”的整个概念是一个过时的思维概念。我的办公桌上有两个屏幕,我公司的几乎每一个屏幕都是如此。你可能想让你的思维模型适应(当前的)现实。

在多个屏幕设置中,居中窗口(在什么上?)是一项艰巨的任务。请参阅此问题如何在Java中居中窗口?及其答案。

匿名用户

使用setLocationRelativeTo(null)行。这将使组件从中间打开。