Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

java - getHeight() and getWidth() method

I wrote a program, expecting it to be displayed in the middle of the screen by using getWidth() and getHeight() methods, but, instead, it appears on the upper left corner. So my question is aren't the getWidth() and getHeight() methods supposed to get the width and height of the whole screen?

/*
 * 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getWidth() / getHeight() are defined in Component, thus they return the size of the component you call them on (in your case this will be a component inside a window).

Check out the Swing tutorial http://docs.oracle.com/javase/tutorial/uiswing/components/ to get an understanding how components are combined to form user interfaces.

Do note that "the screen" is not a Swing object, and that the entire concept of "the screen" is an outdated thinking concept. I have two screens on my desk, and so has almost every one in my company. You may want to adapt your mental model to (current) reality.

Centering a window (on what?) is a non-trivial task in multiple screen setups. Refer to this question How to center a Window in Java? and its answers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...